Artificial Intelligence Nanodegree

Computer Vision Capstone

Project: Facial Keypoint Detection


Welcome to the final Computer Vision project in the Artificial Intelligence Nanodegree program!

In this project, you’ll combine your knowledge of computer vision techniques and deep learning to build and end-to-end facial keypoint recognition system! Facial keypoints include points around the eyes, nose, and mouth on any face and are used in many applications, from facial tracking to emotion recognition.

There are three main parts to this project:

Part 1 : Investigating OpenCV, pre-processing, and face detection

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!


*Here's what you need to know to complete the project:

  1. In this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested.

    a. Sections that begin with '(IMPLEMENTATION)' in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully!

  1. In addition to implementing code, there will be questions that you must answer which relate to the project and your implementation.

    a. Each section where you will answer a question is preceded by a 'Question X' header.

    b. Carefully read each question and provide thorough answers in the following text boxes that begin with 'Answer:'.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. Markdown cells can be edited by double-clicking the cell to enter edit mode.

The rubric contains optional suggestions for enhancing the project beyond the minimum requirements. If you decide to pursue the "(Optional)" sections, you should include the code in this IPython notebook.

Your project submission will be evaluated based on your answers to each of the questions and the code implementations you provide.

Steps to Complete the Project

Each part of the notebook is further broken down into separate steps. Feel free to use the links below to navigate the notebook.

In this project you will get to explore a few of the many computer vision algorithms built into the OpenCV library. This expansive computer vision library is now almost 20 years old and still growing!

The project itself is broken down into three large parts, then even further into separate steps. Make sure to read through each step, and complete any sections that begin with '(IMPLEMENTATION)' in the header; these implementation sections may contain multiple TODOs that will be marked in code. For convenience, we provide links to each of these steps below.

Part 1 : Investigating OpenCV, pre-processing, and face detection

  • Step 0: Detect Faces Using a Haar Cascade Classifier
  • Step 1: Add Eye Detection
  • Step 2: De-noise an Image for Better Face Detection
  • Step 3: Blur an Image and Perform Edge Detection
  • Step 4: Automatically Hide the Identity of an Individual

Part 2 : Training a Convolutional Neural Network (CNN) to detect facial keypoints

  • Step 5: Create a CNN to Recognize Facial Keypoints
  • Step 6: Compile and Train the Model
  • Step 7: Visualize the Loss and Answer Questions

Part 3 : Putting parts 1 and 2 together to identify facial keypoints on any image!

  • Step 8: Build a Robust Facial Keypoints Detector (Complete the CV Pipeline)

Step 0: Detect Faces Using a Haar Cascade Classifier

Have you ever wondered how Facebook automatically tags images with your friends' faces? Or how high-end cameras automatically find and focus on a certain person's face? Applications like these depend heavily on the machine learning task known as face detection - which is the task of automatically finding faces in images containing people.

At its root face detection is a classification problem - that is a problem of distinguishing between distinct classes of things. With face detection these distinct classes are 1) images of human faces and 2) everything else.

We use OpenCV's implementation of Haar feature-based cascade classifiers to detect human faces in images. OpenCV provides many pre-trained face detectors, stored as XML files on github. We have downloaded one of these detectors and stored it in the detector_architectures directory.

Import Resources

In the next python cell, we load in the required libraries for this section of the project.

In [1]:
# Import required libraries for this section

%matplotlib inline

import numpy as np
import matplotlib.pyplot as plt
import math
import cv2                     # OpenCV library for computer vision
from PIL import Image
import time 
from keras.models import load_model
Using TensorFlow backend.

Next, we load in and display a test image for performing face detection.

Note: by default OpenCV assumes the ordering of our image's color channels are Blue, then Green, then Red. This is slightly out of order with most image types we'll use in these experiments, whose color channels are ordered Red, then Green, then Blue. In order to switch the Blue and Red channels of our test image around we will use OpenCV's cvtColor function, which you can read more about by checking out some of its documentation located here. This is a general utility function that can do other transformations too like converting a color image to grayscale, and transforming a standard color image to HSV color space.

In [3]:
# Load in color image for face detection
image = cv2.imread('images/test_image_1.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot our image using subplots to specify a size and title
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[3]:
<matplotlib.image.AxesImage at 0x7f0c18f24cc0>

There are a lot of people - and faces - in this picture. 13 faces to be exact! In the next code cell, we demonstrate how to use a Haar Cascade classifier to detect all the faces in this test image.

This face detector uses information about patterns of intensity in an image to reliably detect faces under varying light conditions. So, to use this face detector, we'll first convert the image from color to grayscale.

Then, we load in the fully trained architecture of the face detector -- found in the file haarcascade_frontalface_default.xml - and use it on our image to find faces!

To learn more about the parameters of the detector see this post.

In [4]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 13
Out[4]:
<matplotlib.image.AxesImage at 0x7f0c18706b38>

In the above code, faces is a numpy array of detected faces, where each row corresponds to a detected face. Each detected face is a 1D array with four entries that specifies the bounding box of the detected face. The first two entries in the array (extracted in the above code as x and y) specify the horizontal and vertical positions of the top left corner of the bounding box. The last two entries in the array (extracted here as w and h) specify the width and height of the box.


Step 1: Add Eye Detections

There are other pre-trained detectors available that use a Haar Cascade Classifier - including full human body detectors, license plate detectors, and more. A full list of the pre-trained architectures can be found here.

To test your eye detector, we'll first read in a new test image with just a single face.

In [4]:
# Load in color image for face detection
image = cv2.imread('images/james.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Plot the RGB image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)
Out[4]:
<matplotlib.image.AxesImage at 0x10c23ac88>

Notice that even though the image is a black and white image, we have read it in as a color image and so it will still need to be converted to grayscale in order to perform the most accurate face detection.

So, the next steps will be to convert this image to grayscale, then load OpenCV's face detector and run it with parameters that detect this face accurately.

In [5]:
# Convert the RGB  image to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 1.25, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detection')
ax1.imshow(image_with_detections)
Number of faces detected: 1
Out[5]:
<matplotlib.image.AxesImage at 0x112a09f28>

(IMPLEMENTATION) Add an eye detector to the current face detection setup.

A Haar-cascade eye detector can be included in the same way that the face detector was and, in this first task, it will be your job to do just this.

To set up an eye detector, use the stored parameters of the eye cascade detector, called haarcascade_eye.xml, located in the detector_architectures subdirectory. In the next code cell, create your eye detector and store its detections.

A few notes before you get started:

First, make sure to give your loaded eye detector the variable name

eye_cascade

and give the list of eye regions you detect the variable name

eyes

Second, since we've already run the face detector over this image, you should only search for eyes within the rectangular face regions detected in faces. This will minimize false detections.

Lastly, once you've run your eye detector over the facial detection region, you should display the RGB image with both the face detection boxes (in red) and your eye detections (in green) to verify that everything works as expected.

In [16]:
# Make a copy of the original image to plot rectangle detections
image_with_detections = np.copy(image)   

# Loop over the detections and draw their corresponding face detection boxes
gray_faces=[]
for (x,y,w,h) in faces:
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h),(255,0,0), 3)
    gray_faces.append(gray[y:y+h, x:x+w])
    
# Do not change the code above this comment!

## DONE: Add eye detection, using haarcascade_eye.xml, to the current face detector algorithm
eye_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_eye.xml')

for (gray_face, (fx, fy, fw, fh)) in zip(gray_faces, faces):
    # we only search for eyes within the gray_faces (rectangular face regions detected in faces)
    eyes = eye_cascade.detectMultiScale(gray_face, 1.15, 6)

    # Print the number of faces detected in the image
    print('Number of eyes detected:', len(eyes))

    ## DONE: Loop over the eye detections and draw their corresponding boxes in green on image_with_detections
    for (x,y,w,h) in eyes:
        # Add a red bounding box to the detections image
        cv2.rectangle(image_with_detections, (fx+x,fy+y), (fx+x+w,fy+y+h), (0,255,0), 3)

# Plot the image with both faces and eyes detected
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face and Eye Detection')
ax1.imshow(image_with_detections)
Number of eyes detected: 2
Out[16]:
<matplotlib.image.AxesImage at 0x114721da0>

(Optional) Add face and eye detection to your laptop camera

It's time to kick it up a notch, and add face and eye detection to your laptop's camera! Afterwards, you'll be able to show off your creation like in the gif shown below - made with a completed version of the code!

Notice that not all of the detections here are perfect - and your result need not be perfect either. You should spend a small amount of time tuning the parameters of your detectors to get reasonable results, but don't hold out for perfection. If we wanted perfection we'd need to spend a ton of time tuning the parameters of each detector, cleaning up the input image frames, etc. You can think of this as more of a rapid prototype.

The next cell contains code for a wrapper function called laptop_camera_face_eye_detector that, when called, will activate your laptop's camera. You will place the relevant face and eye detection code in this wrapper function to implement face/eye detection and mark those detections on each image frame that your camera captures.

Before adding anything to the function, you can run it to get an idea of how it works - a small window should pop up showing you the live feed from your camera; you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [1]:
### Add face and eye detection to this laptop camera function 
# Make sure to draw out all faces/eyes found in each frame on the shown video feed

import cv2
import time 

print('cv2.__version__:', cv2.__version__)

face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_eye.xml')

# wrapper function for face/eye detection with your laptop camera
def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    print('is opened:', vc.isOpened())
    
    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep the video stream open
    while rval:
        # Plot the image from camera with all the face and eye detections marked
        gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.25, 6)
        for (fx,fy,fw,fh) in faces:
            cv2.rectangle(frame, (fx,fy), (fx+fw,fy+fh),(255,0,0), 3)
            # we search for eyes only within the gray_faces (rectangular face regions detected in faces)
            eyes = eye_cascade.detectMultiScale(gray[fy:fy+fh, fx:fx+fw], 1.15, 6)
            for (ex,ey,ew,eh) in eyes:
                cv2.rectangle(frame, (fx+ex,fy+ey), (fx+ex+ew,fy+ey+eh), (0,255,0), 3)
       
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            # Make sure window closes on OSx
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
cv2.__version__: 3.4.0
In [ ]:
# Call the laptop camera face/eye detector function above
laptop_camera_go()
is opened: True

Step 2: De-noise an Image for Better Face Detection

Image quality is an important aspect of any computer vision task. Typically, when creating a set of images to train a deep learning network, significant care is taken to ensure that training images are free of visual noise or artifacts that hinder object detection. While computer vision algorithms - like a face detector - are typically trained on 'nice' data such as this, new test data doesn't always look so nice!

When applying a trained computer vision algorithm to a new piece of test data one often cleans it up first before feeding it in. This sort of cleaning - referred to as pre-processing - can include a number of cleaning phases like blurring, de-noising, color transformations, etc., and many of these tasks can be accomplished using OpenCV.

In this short subsection we explore OpenCV's noise-removal functionality to see how we can clean up a noisy image, which we then feed into our trained face detector.

Create a noisy image to work with

In the next cell, we create an artificial noisy version of the previous multi-face image. This is a little exaggerated - we don't typically get images that are this noisy - but image noise, or 'grainy-ness' in a digitial image - is a fairly common phenomenon.

In [47]:
# Load in the multi-face test image again
image = cv2.imread('images/test_image_1.jpg')

# Convert the image copy to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Make an array copy of this image
image_with_noise = np.asarray(image)

# Create noise - here we add noise sampled randomly from a Gaussian distribution: a common model for noise
noise_level = 40
noise = np.random.randn(image.shape[0],image.shape[1],image.shape[2])*noise_level

# Add this noise to the array image copy
image_with_noise = image_with_noise + noise

# Convert back to uint8 format
image_with_noise = np.asarray([np.uint8(np.clip(i,0,255)) for i in image_with_noise])

# Plot our noisy image!
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image')
ax1.imshow(image_with_noise)
Out[47]:
<matplotlib.image.AxesImage at 0x126d85a58>

In the context of face detection, the problem with an image like this is that - due to noise - we may miss some faces or get false detections.

In the next cell we apply the same trained OpenCV detector with the same settings as before, to see what sort of detections we get.

In [48]:
# Convert the RGB  image to grayscale
gray_noise = cv2.cvtColor(image_with_noise, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_noise, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image_with_noise)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 12
Out[48]:
<matplotlib.image.AxesImage at 0x1241d2b70>

With this added noise we now miss one of the faces!

(IMPLEMENTATION) De-noise this image for better face detection

Time to get your hands dirty: using OpenCV's built in color image de-noising functionality called fastNlMeansDenoisingColored - de-noise this image enough so that all the faces in the image are properly detected. Once you have cleaned the image in the next cell, use the cell that follows to run our trained face detector over the cleaned image to check out its detections.

You can find its official documentation here and a useful example here.

Note: you can keep all parameters except photo_render fixed as shown in the second link above. Play around with the value of this parameter - see how it affects the resulting cleaned image.

In [49]:
## DONE: Use OpenCV's built in color image de-noising function to clean up our noisy image!

# Get final de-noised image (should be RGB)
denoised_image = cv2.fastNlMeansDenoisingColored(image_with_noise, None, 10, 10, 7, 21)
In [50]:
## DONE: Run the face detector on the de-noised image to improve your detections and display the result

# Convert the RGB  image to grayscale
gray_noise = cv2.cvtColor(denoised_image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray_noise, 4, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(denoised_image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    cv2.rectangle(image_with_detections, (x,y), (x+w,y+h), (255,0,0), 3)
    

# Display the image with the detections
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Noisy Image with Face Detections')
ax1.imshow(image_with_detections)
Number of faces detected: 13
Out[50]:
<matplotlib.image.AxesImage at 0x1215cfb70>

Step 3: Blur an Image and Perform Edge Detection

Now that we have developed a simple pipeline for detecting faces using OpenCV - let's start playing around with a few fun things we can do with all those detected faces!

Importance of Blur in Edge Detection

Edge detection is a concept that pops up almost everywhere in computer vision applications, as edge-based features (as well as features built on top of edges) are often some of the best features for e.g., object detection and recognition problems.

Edge detection is a dimension reduction technique - by keeping only the edges of an image we get to throw away a lot of non-discriminating information. And typically the most useful kind of edge-detection is one that preserves only the important, global structures (ignoring local structures that aren't very discriminative). So removing local structures / retaining global structures is a crucial pre-processing step to performing edge detection in an image, and blurring can do just that.

Below is an animated gif showing the result of an edge-detected cat taken from Wikipedia, where the image is gradually blurred more and more prior to edge detection. When the animation begins you can't quite make out what it's a picture of, but as the animation evolves and local structures are removed via blurring the cat becomes visible in the edge-detected image.

Edge detection is a convolution performed on the image itself, and you can read about Canny edge detection on this OpenCV documentation page.

Canny edge detection

In the cell below we load in a test image, then apply Canny edge detection on it. The original image is shown on the left panel of the figure, while the edge-detected version of the image is shown on the right. Notice how the result looks very busy - there are too many little details preserved in the image before it is sent to the edge detector. When applied in computer vision applications, edge detection should preserve global structure; doing away with local structures that don't help describe what objects are in the image.

In [4]:
# Load in the image
image = cv2.imread('images/fawzia.jpg')

# Convert to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)  

# Perform Canny edge detection
edges = cv2.Canny(gray,100,200)

# Dilate the image to amplify edges
edges = cv2.dilate(edges, None)

# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Canny Edges')
ax2.imshow(edges, cmap='gray')
Out[4]:
<matplotlib.image.AxesImage at 0x116744da0>

Without first blurring the image, and removing small, local structures, a lot of irrelevant edge content gets picked up and amplified by the detector (as shown in the right panel above).

(IMPLEMENTATION) Blur the image then perform edge detection

In the next cell, you will repeat this experiment - blurring the image first to remove these local structures, so that only the important boudnary details remain in the edge-detected image.

Blur the image by using OpenCV's filter2d functionality - which is discussed in this documentation page - and use an averaging kernel of width equal to 4.

In [8]:
# Load in the image
image = cv2.imread('images/fawzia.jpg')

# Convert to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)


### DONE: Blur the test image using OpenCV's filter2d functionality, 
# Use an averaging kernel, and a kernel width equal to 4

kernel = np.ones((4,4), np.float32) / 16
gray = cv2.filter2D(gray, -1, kernel)
    
## DONE: Then perform Canny edge detection and display the output

# Perform Canny edge detection
edges = cv2.Canny(gray,100,200)

# Dilate the image to amplify edges
edges = cv2.dilate(edges, None)

# Plot the RGB and edge-detected image
fig = plt.figure(figsize = (15,15))
ax1 = fig.add_subplot(121)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Original Image')
ax1.imshow(image)

ax2 = fig.add_subplot(122)
ax2.set_xticks([])
ax2.set_yticks([])

ax2.set_title('Canny Edges with Blur')
ax2.imshow(edges, cmap='gray')
Out[8]:
<matplotlib.image.AxesImage at 0x117ab7278>

Step 4: Automatically Hide the Identity of an Individual

If you film something like a documentary or reality TV, you must get permission from every individual shown on film before you can show their face, otherwise you need to blur it out - by blurring the face a lot (so much so that even the global structures are obscured)! This is also true for projects like Google's StreetView maps - an enormous collection of mapping images taken from a fleet of Google vehicles. Because it would be impossible for Google to get the permission of every single person accidentally captured in one of these images they blur out everyone's faces, the detected images must automatically blur the identity of detected people. Here's a few examples of folks caught in the camera of a Google street view vehicle.

Read in an image to perform identity detection

Let's try this out for ourselves. Use the face detection pipeline built above and what you know about using the filter2D to blur and image, and use these in tandem to hide the identity of the person in the following image - loaded in and printed in the next cell.

In [9]:
# Load in the image
image = cv2.imread('images/gus.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Display the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[9]:
<matplotlib.image.AxesImage at 0x115d13f28>

(IMPLEMENTATION) Use blurring to hide the identity of an individual in an image

The idea here is to 1) automatically detect the face in this image, and then 2) blur it out! Make sure to adjust the parameters of the averaging blur filter to completely obscure this person's identity.

In [61]:
## DONE: Implement face detection

# Load in the image
image = cv2.imread('images/gus.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# De-noise this image for better face detection
denoised_image = cv2.fastNlMeansDenoisingColored(image, None, 10, 10, 7, 21)

# Convert the RGB  image to grayscale
gray = cv2.cvtColor(denoised_image, cv2.COLOR_RGB2GRAY)

# Extract the pre-trained face detector from an xml file
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

# Detect the faces in image
faces = face_cascade.detectMultiScale(gray, 1.25, 6)

# Print the number of faces detected in the image
print('Number of faces detected:', len(faces))

# Make a copy of the orginal image to draw face detections on
image_with_detections = np.copy(image)

# Get the bounding box for each detected face
for (x,y,w,h) in faces:
    # Add a red bounding box to the detections image
    face_image = image[y:y+h, x:x+w]
    
    ## DONE: Blur the bounding box around each detected face using an averaging filter and display the result
    face_image = cv2.blur(face_image, (50, 50))

    image_with_detections[y:y+h, x:x+w] = face_image

# Display the image with the detections
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])

ax1.set_title('Image with Face Detection')
ax1.imshow(image_with_detections)
Number of faces detected: 1
Out[61]:
<matplotlib.image.AxesImage at 0x1367eb390>

(Optional) Build identity protection into your laptop camera

In this optional task you can add identity protection to your laptop camera, using the previously completed code where you added face detection to your laptop camera - and the task above. You should be able to get reasonable results with little parameter tuning - like the one shown in the gif below.

As with the previous video task, to make this perfect would require significant effort - so don't strive for perfection here, strive for reasonable quality.

The next cell contains code a wrapper function called laptop_camera_identity_hider that - when called - will activate your laptop's camera. You need to place the relevant face detection and blurring code developed above in this function in order to blur faces entering your laptop camera's field of view.

Before adding anything to the function you can call it to get a hang of how it works - a small window will pop up showing you the live feed from your camera, you can press any key to close this window.

Note: Mac users may find that activating this function kills the kernel of their notebook every once in a while. If this happens to you, just restart your notebook's kernel, activate cell(s) containing any crucial import statements, and you'll be good to go!

In [1]:
### Insert face detection and blurring code into the wrapper below to create an identity protector on your laptop!
import cv2
import time 

face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
    
def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep video stream open
    while rval:
        # Plot image from camera with detections marked
        
        gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.25, 6)
        for (x,y,w,h) in faces:
            face_image = frame[y:y+h, x:x+w]
            face_image = cv2.blur(face_image, (50, 50))
            frame[y:y+h, x:x+w] = face_image
        
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # Exit by pressing any key
            # Destroy windows
            cv2.destroyAllWindows()
            
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
        
In [ ]:
# Run laptop identity hider
laptop_camera_go()

Step 5: Create a CNN to Recognize Facial Keypoints

OpenCV is often used in practice with other machine learning and deep learning libraries to produce interesting results. In this stage of the project you will create your own end-to-end pipeline - employing convolutional networks in keras along with OpenCV - to apply a "selfie" filter to streaming video and images.

You will start by creating and then training a convolutional network that can detect facial keypoints in a small dataset of cropped images of human faces. We then guide you towards OpenCV to expanding your detection algorithm to more general images. What are facial keypoints? Let's take a look at some examples.

Facial keypoints (also called facial landmarks) are the small blue-green dots shown on each of the faces in the image above - there are 15 keypoints marked in each image. They mark important areas of the face - the eyes, corners of the mouth, the nose, etc. Facial keypoints can be used in a variety of machine learning applications from face and emotion recognition to commercial applications like the image filters popularized by Snapchat.

Below we illustrate a filter that, using the results of this section, automatically places sunglasses on people in images (using the facial keypoints to place the glasses correctly on each face). Here, the facial keypoints have been colored lime green for visualization purposes.

Make a facial keypoint detector

But first things first: how can we make a facial keypoint detector? Well, at a high level, notice that facial keypoint detection is a regression problem. A single face corresponds to a set of 15 facial keypoints (a set of 15 corresponding $(x, y)$ coordinates, i.e., an output point). Because our input data are images, we can employ a convolutional neural network to recognize patterns in our images and learn how to identify these keypoint given sets of labeled data.

In order to train a regressor, we need a training set - a set of facial image / facial keypoint pairs to train on. For this we will be using this dataset from Kaggle. We've already downloaded this data and placed it in the data directory. Make sure that you have both the training and test data files. The training dataset contains several thousand $96 \times 96$ grayscale images of cropped human faces, along with each face's 15 corresponding facial keypoints (also called landmarks) that have been placed by hand, and recorded in $(x, y)$ coordinates. This wonderful resource also has a substantial testing set, which we will use in tinkering with our convolutional network.

To load in this data, run the Python cell below - notice we will load in both the training and testing sets.

The load_data function is in the included utils.py file.

In [2]:
from utils import *

# Load training set
X_train, y_train = load_data()
print("X_train.shape == {}".format(X_train.shape))
print("y_train.shape == {}; y_train.min == {:.3f}; y_train.max == {:.3f}".format(
    y_train.shape, y_train.min(), y_train.max()))

# Load testing set
X_test, _ = load_data(test=True)
print("X_test.shape == {}".format(X_test.shape))
X_train.shape == (2140, 96, 96, 1)
y_train.shape == (2140, 30); y_train.min == -0.920; y_train.max == 0.996
X_test.shape == (1783, 96, 96, 1)

The load_data function in utils.py originates from this excellent blog post, which you are strongly encouraged to read. Please take the time now to review this function. Note how the output values - that is, the coordinates of each set of facial landmarks - have been normalized to take on values in the range $[-1, 1]$, while the pixel values of each input point (a facial image) have been normalized to the range $[0,1]$.

Note: the original Kaggle dataset contains some images with several missing keypoints. For simplicity, the load_data function removes those images with missing labels from the dataset. As an optional extension, you are welcome to amend the load_data function to include the incomplete data points.

Visualize the Training Data

Execute the code cell below to visualize a subset of the training data.

In [3]:
import matplotlib.pyplot as plt
%matplotlib inline

fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_train[i], y_train[i], ax)

For each training image, there are two landmarks per eyebrow (four total), three per eye (six total), four for the mouth, and one for the tip of the nose.

Review the plot_data function in utils.py to understand how the 30-dimensional training labels in y_train are mapped to facial locations, as this function will prove useful for your pipeline.

(IMPLEMENTATION) Specify the CNN Architecture

In this section, you will specify a neural network for predicting the locations of facial keypoints. Use the code cell below to specify the architecture of your neural network. We have imported some layers that you may find useful for this task, but if you need to use more Keras layers, feel free to import them in the cell.

Your network should accept a $96 \times 96$ grayscale image as input, and it should output a vector with 30 entries, corresponding to the predicted (horizontal and vertical) locations of 15 facial keypoints. If you are not sure where to start, you can find some useful starting architectures in this blog, but you are not permitted to copy any of the architectures that you find online.

In [3]:
# Import deep learning resources from Keras
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D, Dropout
from keras.layers import Flatten, Dense


## TODO: Specify a CNN architecture
# Your model should accept 96x96 pixel graysale images in
# It should have a fully-connected output layer with 30 values (2 for each facial keypoint)

input_shape = X_train.shape[1:]
num_classes = y_train.shape[1]
print('input_shape:', input_shape)
print('num_classes:', num_classes)

model = Sequential()

model.add(Convolution2D(filters=128, kernel_size=(3, 3), padding='same', activation='relu', 
                        input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(filters=64, kernel_size=(3, 3), padding='same', activation='relu', 
                        input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Convolution2D(filters=32, kernel_size=(3, 3), padding='same', activation='relu', 
                        input_shape=input_shape))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(100))
model.add(Dropout(0.2))
model.add(Dense(100))
model.add(Dropout(0.2))
model.add(Dense(num_classes, activation='linear'))

# Summarize the model
model.summary()
input_shape: (96, 96, 1)
num_classes: 30
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 96, 96, 128)       1280      
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 48, 48, 128)       0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 48, 48, 64)        73792     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 24, 24, 64)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 24, 24, 32)        18464     
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 12, 12, 32)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 4608)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 100)               460900    
_________________________________________________________________
dropout_1 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 100)               10100     
_________________________________________________________________
dropout_2 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                3030      
=================================================================
Total params: 567,566
Trainable params: 567,566
Non-trainable params: 0
_________________________________________________________________

Step 6: Compile and Train the Model

After specifying your architecture, you'll need to compile and train the model to detect facial keypoints'

(IMPLEMENTATION) Compile and Train the Model

Use the compile method to configure the learning process. Experiment with your choice of optimizer; you may have some ideas about which will work best (SGD vs. RMSprop, etc), but take the time to empirically verify your theories.

Use the fit method to train the model. Break off a validation set by setting validation_split=0.2. Save the returned History object in the history variable.

Experiment with your model to minimize the validation loss (measured as mean squared error). A very good model will achieve about 0.0015 loss (though it's possible to do even better). When you have finished training, save your model as an HDF5 file with file path my_model.h5.

In [21]:
from keras.optimizers import SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam
from keras.callbacks import EarlyStopping, TensorBoard

optimizer = dict()
optimizer['sgd'] = SGD(lr=0.01, momentum=0.0, decay=0.0, nesterov=False)
optimizer['rmsprop'] = RMSprop(lr=0.001, rho=0.9, decay=0.0)
optimizer['adagrad'] = Adagrad(lr=0.01, decay=0.0)
optimizer['adadelta'] = Adadelta(lr=1.0, rho=0.95, decay=0.0)
optimizer['adam'] = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, decay=0.0)
optimizer['adamax'] = Adamax(lr=0.002, beta_1=0.9, beta_2=0.999, decay=0.0)
optimizer['nadam'] = Nadam(lr=0.002, beta_1=0.9, beta_2=0.999, schedule_decay=0.004)


validation_split=0.2

history = dict()

def compile_train_save_model(optimizer_id, epochs=1000, batch_size = 32, callbacks=[
    EarlyStopping(monitor='val_loss', min_delta=0, patience=5, verbose=1, mode='auto'),
    TensorBoard(log_dir='./logs', histogram_freq=0, batch_size=batch_size, write_graph=True, write_grads=False, embeddings_freq=0)    
]):
    model.summary()
    
    print('Compile, train and save model for {}'.format(optimizer_id))

    ## DONE: Compile the model
    model.compile(loss='mean_squared_error',
                  optimizer=optimizer[optimizer_id],
                  metrics=['accuracy'])

    ## DONE: Train the model
    history[optimizer_id] = model.fit(X_train, y_train,
                                batch_size = batch_size, epochs = epochs, verbose=2,
                                validation_split=validation_split, callbacks=callbacks)

    ## DONE: Save the model as model.h5
    model.save('my_model.h5')
    model.save('my_model_{}.h5'.format(optimizer_id))
In [5]:
# SGD optimizer

compile_train_save_model('sgd')
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 96, 96, 128)       1280      
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 48, 48, 128)       0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 48, 48, 64)        73792     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 24, 24, 64)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 24, 24, 32)        18464     
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 12, 12, 32)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 4608)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 100)               460900    
_________________________________________________________________
dropout_1 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 100)               10100     
_________________________________________________________________
dropout_2 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                3030      
=================================================================
Total params: 567,566
Trainable params: 567,566
Non-trainable params: 0
_________________________________________________________________
Compile, train and save model for sgd
Train on 1712 samples, validate on 428 samples
Epoch 1/1000
4s - loss: 0.0944 - acc: 0.3972 - val_loss: 0.0293 - val_acc: 0.6706
Epoch 2/1000
3s - loss: 0.0418 - acc: 0.3633 - val_loss: 0.0149 - val_acc: 0.7009
Epoch 3/1000
3s - loss: 0.0345 - acc: 0.3867 - val_loss: 0.0127 - val_acc: 0.6986
Epoch 4/1000
3s - loss: 0.0311 - acc: 0.3861 - val_loss: 0.0110 - val_acc: 0.6986
Epoch 5/1000
3s - loss: 0.0281 - acc: 0.3943 - val_loss: 0.0104 - val_acc: 0.6986
Epoch 6/1000
3s - loss: 0.0264 - acc: 0.4118 - val_loss: 0.0095 - val_acc: 0.6963
Epoch 7/1000
3s - loss: 0.0248 - acc: 0.4246 - val_loss: 0.0091 - val_acc: 0.6963
Epoch 8/1000
3s - loss: 0.0234 - acc: 0.4083 - val_loss: 0.0080 - val_acc: 0.6963
Epoch 9/1000
3s - loss: 0.0223 - acc: 0.4147 - val_loss: 0.0079 - val_acc: 0.6963
Epoch 10/1000
3s - loss: 0.0214 - acc: 0.4153 - val_loss: 0.0076 - val_acc: 0.6963
Epoch 11/1000
3s - loss: 0.0208 - acc: 0.4229 - val_loss: 0.0072 - val_acc: 0.6963
Epoch 12/1000
3s - loss: 0.0198 - acc: 0.4375 - val_loss: 0.0070 - val_acc: 0.6963
Epoch 13/1000
3s - loss: 0.0195 - acc: 0.4363 - val_loss: 0.0066 - val_acc: 0.6963
Epoch 14/1000
3s - loss: 0.0189 - acc: 0.4463 - val_loss: 0.0066 - val_acc: 0.6963
Epoch 15/1000
4s - loss: 0.0181 - acc: 0.4416 - val_loss: 0.0064 - val_acc: 0.6963
Epoch 16/1000
4s - loss: 0.0178 - acc: 0.4474 - val_loss: 0.0067 - val_acc: 0.6963
Epoch 17/1000
4s - loss: 0.0173 - acc: 0.4568 - val_loss: 0.0062 - val_acc: 0.6963
Epoch 18/1000
4s - loss: 0.0170 - acc: 0.4574 - val_loss: 0.0064 - val_acc: 0.6963
Epoch 19/1000
4s - loss: 0.0167 - acc: 0.4579 - val_loss: 0.0059 - val_acc: 0.6963
Epoch 20/1000
4s - loss: 0.0160 - acc: 0.4591 - val_loss: 0.0063 - val_acc: 0.6963
Epoch 21/1000
4s - loss: 0.0159 - acc: 0.4504 - val_loss: 0.0060 - val_acc: 0.6963
Epoch 22/1000
4s - loss: 0.0154 - acc: 0.4936 - val_loss: 0.0057 - val_acc: 0.6963
Epoch 23/1000
4s - loss: 0.0152 - acc: 0.4638 - val_loss: 0.0061 - val_acc: 0.6963
Epoch 24/1000
4s - loss: 0.0149 - acc: 0.4825 - val_loss: 0.0060 - val_acc: 0.6963
Epoch 25/1000
4s - loss: 0.0146 - acc: 0.4836 - val_loss: 0.0058 - val_acc: 0.6963
Epoch 26/1000
4s - loss: 0.0145 - acc: 0.4848 - val_loss: 0.0059 - val_acc: 0.6963
Epoch 27/1000
4s - loss: 0.0140 - acc: 0.4708 - val_loss: 0.0058 - val_acc: 0.6963
Epoch 28/1000
4s - loss: 0.0139 - acc: 0.4930 - val_loss: 0.0057 - val_acc: 0.6963
Epoch 29/1000
4s - loss: 0.0136 - acc: 0.5041 - val_loss: 0.0054 - val_acc: 0.6963
Epoch 30/1000
4s - loss: 0.0135 - acc: 0.4755 - val_loss: 0.0059 - val_acc: 0.6963
Epoch 31/1000
4s - loss: 0.0134 - acc: 0.4971 - val_loss: 0.0057 - val_acc: 0.6963
Epoch 32/1000
4s - loss: 0.0132 - acc: 0.4965 - val_loss: 0.0055 - val_acc: 0.6963
Epoch 33/1000
4s - loss: 0.0130 - acc: 0.5111 - val_loss: 0.0055 - val_acc: 0.6963
Epoch 34/1000
4s - loss: 0.0130 - acc: 0.4959 - val_loss: 0.0057 - val_acc: 0.6963
Epoch 35/1000
4s - loss: 0.0127 - acc: 0.5000 - val_loss: 0.0055 - val_acc: 0.6963
Epoch 00034: early stopping
In [6]:
# RMSprop optimizer

compile_train_save_model('rmsprop')
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 96, 96, 128)       1280      
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 48, 48, 128)       0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 48, 48, 64)        73792     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 24, 24, 64)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 24, 24, 32)        18464     
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 12, 12, 32)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 4608)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 100)               460900    
_________________________________________________________________
dropout_1 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 100)               10100     
_________________________________________________________________
dropout_2 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                3030      
=================================================================
Total params: 567,566
Trainable params: 567,566
Non-trainable params: 0
_________________________________________________________________
Compile, train and save model for rmsprop
Train on 1712 samples, validate on 428 samples
Epoch 1/1000
4s - loss: 0.0262 - acc: 0.5333 - val_loss: 0.0052 - val_acc: 0.6963
Epoch 2/1000
4s - loss: 0.0093 - acc: 0.6174 - val_loss: 0.0044 - val_acc: 0.6963
Epoch 3/1000
4s - loss: 0.0060 - acc: 0.6647 - val_loss: 0.0036 - val_acc: 0.7033
Epoch 4/1000
4s - loss: 0.0049 - acc: 0.6682 - val_loss: 0.0034 - val_acc: 0.6939
Epoch 5/1000
4s - loss: 0.0038 - acc: 0.6980 - val_loss: 0.0023 - val_acc: 0.7220
Epoch 6/1000
4s - loss: 0.0033 - acc: 0.7138 - val_loss: 0.0021 - val_acc: 0.7453
Epoch 7/1000
4s - loss: 0.0028 - acc: 0.7173 - val_loss: 0.0019 - val_acc: 0.7453
Epoch 8/1000
4s - loss: 0.0027 - acc: 0.7214 - val_loss: 0.0029 - val_acc: 0.7056
Epoch 9/1000
4s - loss: 0.0024 - acc: 0.7325 - val_loss: 0.0022 - val_acc: 0.7173
Epoch 10/1000
4s - loss: 0.0022 - acc: 0.7459 - val_loss: 0.0022 - val_acc: 0.7570
Epoch 11/1000
4s - loss: 0.0021 - acc: 0.7465 - val_loss: 0.0021 - val_acc: 0.6986
Epoch 12/1000
4s - loss: 0.0020 - acc: 0.7541 - val_loss: 0.0015 - val_acc: 0.7850
Epoch 13/1000
4s - loss: 0.0019 - acc: 0.7523 - val_loss: 0.0015 - val_acc: 0.7780
Epoch 14/1000
4s - loss: 0.0018 - acc: 0.7605 - val_loss: 0.0015 - val_acc: 0.7734
Epoch 15/1000
4s - loss: 0.0017 - acc: 0.7704 - val_loss: 0.0015 - val_acc: 0.7897
Epoch 16/1000
4s - loss: 0.0016 - acc: 0.7564 - val_loss: 0.0016 - val_acc: 0.7757
Epoch 17/1000
4s - loss: 0.0016 - acc: 0.7728 - val_loss: 0.0018 - val_acc: 0.7967
Epoch 18/1000
4s - loss: 0.0016 - acc: 0.7687 - val_loss: 0.0017 - val_acc: 0.8084
Epoch 19/1000
4s - loss: 0.0015 - acc: 0.7687 - val_loss: 0.0015 - val_acc: 0.7804
Epoch 20/1000
4s - loss: 0.0014 - acc: 0.7868 - val_loss: 0.0017 - val_acc: 0.7617
Epoch 00019: early stopping
In [7]:
# Adagrad optimizer

compile_train_save_model('adagrad')
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 96, 96, 128)       1280      
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 48, 48, 128)       0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 48, 48, 64)        73792     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 24, 24, 64)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 24, 24, 32)        18464     
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 12, 12, 32)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 4608)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 100)               460900    
_________________________________________________________________
dropout_1 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 100)               10100     
_________________________________________________________________
dropout_2 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                3030      
=================================================================
Total params: 567,566
Trainable params: 567,566
Non-trainable params: 0
_________________________________________________________________
Compile, train and save model for adagrad
Train on 1712 samples, validate on 428 samples
Epoch 1/1000
4s - loss: 0.0522 - acc: 0.6513 - val_loss: 0.0044 - val_acc: 0.6963
Epoch 2/1000
3s - loss: 0.0047 - acc: 0.7062 - val_loss: 0.0044 - val_acc: 0.6963
Epoch 3/1000
3s - loss: 0.0046 - acc: 0.7085 - val_loss: 0.0042 - val_acc: 0.6963
Epoch 4/1000
3s - loss: 0.0044 - acc: 0.7039 - val_loss: 0.0038 - val_acc: 0.7009
Epoch 5/1000
3s - loss: 0.0042 - acc: 0.6998 - val_loss: 0.0035 - val_acc: 0.6893
Epoch 6/1000
3s - loss: 0.0027 - acc: 0.7155 - val_loss: 0.0021 - val_acc: 0.7266
Epoch 7/1000
3s - loss: 0.0023 - acc: 0.7068 - val_loss: 0.0020 - val_acc: 0.7196
Epoch 8/1000
3s - loss: 0.0021 - acc: 0.7383 - val_loss: 0.0019 - val_acc: 0.7173
Epoch 9/1000
3s - loss: 0.0020 - acc: 0.7243 - val_loss: 0.0019 - val_acc: 0.7173
Epoch 10/1000
3s - loss: 0.0019 - acc: 0.7237 - val_loss: 0.0018 - val_acc: 0.7407
Epoch 11/1000
3s - loss: 0.0019 - acc: 0.7301 - val_loss: 0.0017 - val_acc: 0.7196
Epoch 12/1000
3s - loss: 0.0018 - acc: 0.7389 - val_loss: 0.0017 - val_acc: 0.7126
Epoch 13/1000
3s - loss: 0.0018 - acc: 0.7389 - val_loss: 0.0016 - val_acc: 0.7196
Epoch 14/1000
3s - loss: 0.0018 - acc: 0.7290 - val_loss: 0.0016 - val_acc: 0.7430
Epoch 15/1000
3s - loss: 0.0017 - acc: 0.7395 - val_loss: 0.0016 - val_acc: 0.7220
Epoch 16/1000
3s - loss: 0.0016 - acc: 0.7412 - val_loss: 0.0017 - val_acc: 0.7313
Epoch 17/1000
3s - loss: 0.0016 - acc: 0.7535 - val_loss: 0.0015 - val_acc: 0.7477
Epoch 18/1000
3s - loss: 0.0016 - acc: 0.7634 - val_loss: 0.0015 - val_acc: 0.7336
Epoch 19/1000
3s - loss: 0.0016 - acc: 0.7401 - val_loss: 0.0015 - val_acc: 0.7383
Epoch 20/1000
3s - loss: 0.0015 - acc: 0.7471 - val_loss: 0.0016 - val_acc: 0.7336
Epoch 21/1000
3s - loss: 0.0015 - acc: 0.7570 - val_loss: 0.0015 - val_acc: 0.7477
Epoch 22/1000
3s - loss: 0.0015 - acc: 0.7588 - val_loss: 0.0015 - val_acc: 0.7477
Epoch 23/1000
3s - loss: 0.0015 - acc: 0.7588 - val_loss: 0.0015 - val_acc: 0.7453
Epoch 24/1000
3s - loss: 0.0014 - acc: 0.7547 - val_loss: 0.0014 - val_acc: 0.7477
Epoch 25/1000
3s - loss: 0.0014 - acc: 0.7617 - val_loss: 0.0016 - val_acc: 0.7477
Epoch 26/1000
3s - loss: 0.0014 - acc: 0.7669 - val_loss: 0.0014 - val_acc: 0.7710
Epoch 27/1000
3s - loss: 0.0014 - acc: 0.7518 - val_loss: 0.0014 - val_acc: 0.7430
Epoch 28/1000
3s - loss: 0.0013 - acc: 0.7623 - val_loss: 0.0014 - val_acc: 0.7617
Epoch 29/1000
3s - loss: 0.0014 - acc: 0.7611 - val_loss: 0.0015 - val_acc: 0.7523
Epoch 30/1000
3s - loss: 0.0014 - acc: 0.7605 - val_loss: 0.0014 - val_acc: 0.7593
Epoch 31/1000
3s - loss: 0.0014 - acc: 0.7699 - val_loss: 0.0014 - val_acc: 0.7547
Epoch 32/1000
3s - loss: 0.0013 - acc: 0.7757 - val_loss: 0.0014 - val_acc: 0.7593
Epoch 33/1000
3s - loss: 0.0013 - acc: 0.7821 - val_loss: 0.0014 - val_acc: 0.7687
Epoch 34/1000
3s - loss: 0.0013 - acc: 0.7874 - val_loss: 0.0014 - val_acc: 0.7664
Epoch 35/1000
3s - loss: 0.0013 - acc: 0.7769 - val_loss: 0.0014 - val_acc: 0.7710
Epoch 36/1000
3s - loss: 0.0013 - acc: 0.7728 - val_loss: 0.0014 - val_acc: 0.7570
Epoch 37/1000
3s - loss: 0.0012 - acc: 0.7710 - val_loss: 0.0014 - val_acc: 0.7617
Epoch 38/1000
3s - loss: 0.0012 - acc: 0.7845 - val_loss: 0.0014 - val_acc: 0.7617
Epoch 39/1000
3s - loss: 0.0012 - acc: 0.7675 - val_loss: 0.0014 - val_acc: 0.7617
Epoch 00038: early stopping
In [8]:
# Adadelta optimizer

compile_train_save_model('adadelta')
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 96, 96, 128)       1280      
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 48, 48, 128)       0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 48, 48, 64)        73792     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 24, 24, 64)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 24, 24, 32)        18464     
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 12, 12, 32)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 4608)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 100)               460900    
_________________________________________________________________
dropout_1 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 100)               10100     
_________________________________________________________________
dropout_2 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                3030      
=================================================================
Total params: 567,566
Trainable params: 567,566
Non-trainable params: 0
_________________________________________________________________
Compile, train and save model for adadelta
Train on 1712 samples, validate on 428 samples
Epoch 1/1000
4s - loss: 0.0012 - acc: 0.7827 - val_loss: 0.0014 - val_acc: 0.7640
Epoch 2/1000
4s - loss: 0.0012 - acc: 0.7763 - val_loss: 0.0014 - val_acc: 0.7780
Epoch 3/1000
4s - loss: 0.0012 - acc: 0.7775 - val_loss: 0.0014 - val_acc: 0.7640
Epoch 4/1000
4s - loss: 0.0012 - acc: 0.7961 - val_loss: 0.0014 - val_acc: 0.7687
Epoch 5/1000
4s - loss: 0.0012 - acc: 0.7734 - val_loss: 0.0014 - val_acc: 0.7850
Epoch 6/1000
4s - loss: 0.0012 - acc: 0.7845 - val_loss: 0.0014 - val_acc: 0.7687
Epoch 7/1000
4s - loss: 0.0012 - acc: 0.7775 - val_loss: 0.0015 - val_acc: 0.7850
Epoch 00006: early stopping
In [9]:
# Adam optimizer

compile_train_save_model('adam')
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 96, 96, 128)       1280      
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 48, 48, 128)       0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 48, 48, 64)        73792     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 24, 24, 64)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 24, 24, 32)        18464     
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 12, 12, 32)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 4608)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 100)               460900    
_________________________________________________________________
dropout_1 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 100)               10100     
_________________________________________________________________
dropout_2 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                3030      
=================================================================
Total params: 567,566
Trainable params: 567,566
Non-trainable params: 0
_________________________________________________________________
Compile, train and save model for adam
Train on 1712 samples, validate on 428 samples
Epoch 1/1000
4s - loss: 0.0015 - acc: 0.7634 - val_loss: 0.0015 - val_acc: 0.7593
Epoch 2/1000
4s - loss: 0.0013 - acc: 0.7845 - val_loss: 0.0014 - val_acc: 0.7804
Epoch 3/1000
4s - loss: 0.0013 - acc: 0.7839 - val_loss: 0.0015 - val_acc: 0.7734
Epoch 4/1000
4s - loss: 0.0012 - acc: 0.7868 - val_loss: 0.0014 - val_acc: 0.7500
Epoch 5/1000
4s - loss: 0.0012 - acc: 0.7903 - val_loss: 0.0013 - val_acc: 0.7687
Epoch 6/1000
4s - loss: 0.0012 - acc: 0.7915 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 7/1000
4s - loss: 0.0011 - acc: 0.8002 - val_loss: 0.0014 - val_acc: 0.7921
Epoch 8/1000
4s - loss: 0.0011 - acc: 0.7938 - val_loss: 0.0013 - val_acc: 0.7734
Epoch 9/1000
4s - loss: 0.0011 - acc: 0.8014 - val_loss: 0.0013 - val_acc: 0.7617
Epoch 10/1000
4s - loss: 0.0011 - acc: 0.8032 - val_loss: 0.0013 - val_acc: 0.7757
Epoch 11/1000
4s - loss: 0.0010 - acc: 0.8096 - val_loss: 0.0014 - val_acc: 0.7547
Epoch 12/1000
4s - loss: 0.0010 - acc: 0.8084 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 13/1000
4s - loss: 9.5676e-04 - acc: 0.8090 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 14/1000
4s - loss: 9.4716e-04 - acc: 0.8125 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 15/1000
4s - loss: 9.4486e-04 - acc: 0.8096 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 16/1000
4s - loss: 9.0187e-04 - acc: 0.8213 - val_loss: 0.0013 - val_acc: 0.8107
Epoch 17/1000
4s - loss: 9.0168e-04 - acc: 0.8306 - val_loss: 0.0012 - val_acc: 0.8061
Epoch 18/1000
4s - loss: 8.7147e-04 - acc: 0.8254 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 19/1000
4s - loss: 8.6173e-04 - acc: 0.8218 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 20/1000
4s - loss: 8.4612e-04 - acc: 0.8189 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 21/1000
4s - loss: 8.1852e-04 - acc: 0.8195 - val_loss: 0.0012 - val_acc: 0.7921
Epoch 22/1000
4s - loss: 8.1580e-04 - acc: 0.8277 - val_loss: 0.0012 - val_acc: 0.8014
Epoch 23/1000
4s - loss: 8.1174e-04 - acc: 0.8148 - val_loss: 0.0012 - val_acc: 0.7944
Epoch 24/1000
4s - loss: 7.7572e-04 - acc: 0.8312 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 25/1000
4s - loss: 7.9473e-04 - acc: 0.8376 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 26/1000
4s - loss: 7.8524e-04 - acc: 0.8242 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 27/1000
4s - loss: 7.7007e-04 - acc: 0.8189 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 28/1000
4s - loss: 7.5710e-04 - acc: 0.8306 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 00027: early stopping
In [12]:
# Adamax optimizer

compile_train_save_model('adamax')
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 96, 96, 128)       1280      
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 48, 48, 128)       0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 48, 48, 64)        73792     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 24, 24, 64)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 24, 24, 32)        18464     
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 12, 12, 32)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 4608)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 100)               460900    
_________________________________________________________________
dropout_1 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 100)               10100     
_________________________________________________________________
dropout_2 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                3030      
=================================================================
Total params: 567,566
Trainable params: 567,566
Non-trainable params: 0
_________________________________________________________________
Compile, train and save model for adamax
Train on 1712 samples, validate on 428 samples
Epoch 1/1000
4s - loss: 7.9013e-04 - acc: 0.8312 - val_loss: 0.0012 - val_acc: 0.7897
Epoch 2/1000
3s - loss: 6.2594e-04 - acc: 0.8400 - val_loss: 0.0012 - val_acc: 0.7967
Epoch 3/1000
3s - loss: 5.9490e-04 - acc: 0.8458 - val_loss: 0.0012 - val_acc: 0.7874
Epoch 4/1000
3s - loss: 5.8195e-04 - acc: 0.8522 - val_loss: 0.0012 - val_acc: 0.8037
Epoch 5/1000
3s - loss: 5.7654e-04 - acc: 0.8400 - val_loss: 0.0012 - val_acc: 0.7850
Epoch 6/1000
3s - loss: 5.7283e-04 - acc: 0.8452 - val_loss: 0.0012 - val_acc: 0.7827
Epoch 7/1000
4s - loss: 5.6922e-04 - acc: 0.8575 - val_loss: 0.0012 - val_acc: 0.7921
Epoch 8/1000
4s - loss: 5.6494e-04 - acc: 0.8551 - val_loss: 0.0012 - val_acc: 0.8037
Epoch 9/1000
4s - loss: 5.5051e-04 - acc: 0.8621 - val_loss: 0.0012 - val_acc: 0.8061
Epoch 10/1000
4s - loss: 5.5462e-04 - acc: 0.8546 - val_loss: 0.0012 - val_acc: 0.7991
Epoch 11/1000
4s - loss: 5.4388e-04 - acc: 0.8435 - val_loss: 0.0012 - val_acc: 0.7921
Epoch 12/1000
4s - loss: 5.4965e-04 - acc: 0.8557 - val_loss: 0.0012 - val_acc: 0.7874
Epoch 13/1000
4s - loss: 5.4525e-04 - acc: 0.8364 - val_loss: 0.0012 - val_acc: 0.7991
Epoch 14/1000
4s - loss: 5.3750e-04 - acc: 0.8505 - val_loss: 0.0012 - val_acc: 0.7944
Epoch 15/1000
4s - loss: 5.4107e-04 - acc: 0.8394 - val_loss: 0.0012 - val_acc: 0.7944
Epoch 16/1000
4s - loss: 5.2372e-04 - acc: 0.8534 - val_loss: 0.0012 - val_acc: 0.7991
Epoch 17/1000
4s - loss: 5.2693e-04 - acc: 0.8534 - val_loss: 0.0012 - val_acc: 0.7991
Epoch 00016: early stopping
In [10]:
# Nadam optimizer

compile_train_save_model('nadam')
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 96, 96, 128)       1280      
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 48, 48, 128)       0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 48, 48, 64)        73792     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 24, 24, 64)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 24, 24, 32)        18464     
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 12, 12, 32)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 4608)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 100)               460900    
_________________________________________________________________
dropout_1 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 100)               10100     
_________________________________________________________________
dropout_2 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                3030      
=================================================================
Total params: 567,566
Trainable params: 567,566
Non-trainable params: 0
_________________________________________________________________
Compile, train and save model for nadam
Train on 1712 samples, validate on 428 samples
Epoch 1/1000
4s - loss: 0.0014 - acc: 0.8090 - val_loss: 0.0015 - val_acc: 0.7640
Epoch 2/1000
4s - loss: 8.6520e-04 - acc: 0.8230 - val_loss: 0.0015 - val_acc: 0.7757
Epoch 3/1000
4s - loss: 8.5326e-04 - acc: 0.8201 - val_loss: 0.0017 - val_acc: 0.7173
Epoch 4/1000
4s - loss: 9.4356e-04 - acc: 0.8113 - val_loss: 0.0014 - val_acc: 0.7757
Epoch 5/1000
4s - loss: 8.5678e-04 - acc: 0.8172 - val_loss: 0.0014 - val_acc: 0.7804
Epoch 6/1000
4s - loss: 8.5017e-04 - acc: 0.8172 - val_loss: 0.0014 - val_acc: 0.7897
Epoch 7/1000
4s - loss: 8.7197e-04 - acc: 0.8172 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 8/1000
4s - loss: 8.5759e-04 - acc: 0.8201 - val_loss: 0.0014 - val_acc: 0.7687
Epoch 9/1000
4s - loss: 8.7645e-04 - acc: 0.8166 - val_loss: 0.0016 - val_acc: 0.7710
Epoch 10/1000
4s - loss: 8.5764e-04 - acc: 0.8300 - val_loss: 0.0016 - val_acc: 0.8014
Epoch 11/1000
4s - loss: 8.1968e-04 - acc: 0.8131 - val_loss: 0.0014 - val_acc: 0.7453
Epoch 12/1000
4s - loss: 8.1045e-04 - acc: 0.8254 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 13/1000
4s - loss: 7.3185e-04 - acc: 0.8400 - val_loss: 0.0014 - val_acc: 0.7734
Epoch 00012: early stopping

Step 7: Visualize the Loss and Test Predictions

(IMPLEMENTATION) Answer a few questions and visualize the loss

Question 1: Outline the steps you took to get to your final neural network architecture and your reasoning at each step.

Answer:

Initially, I set maximum 1000 epochs of training with adding EarlyStopping callback to simplify choosing number of epochs for training. I also setup TensorBoard callbacks to store logs of training and see them in TensorBoard application.

I had the following milestones:

  1. I stated with creating architecture of convolutional neural network with three different layers: a Convolution2D (32 filters; 3x3 kernel, relu activation), a Flatten and a Dense layer with (30 neurons and linear activation). Initially I used Adam optimizer. On the step I got the following training results for accuracy and loss:
    Epoch 15/1000
    1s - loss: 8.4590e-04 - acc: 0.8429 - val_loss: 0.0044 - val_acc: 0.6869
  2. Added a MaxPooling2D (2x2 pool) after convolutional layer with (30 neurons and linear activation).
    Epoch 21/1000
    0s - loss: 2.6155e-04 - acc: 0.9065 - val_loss: 0.0020 - val_acc: 0.8014
  3. Trained the model above with SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam optimizers. The best result gave me out Adamax optimizer:
    Epoch 6/1000
    0s - loss: 8.3116e-05 - acc: 0.9492 - val_loss: 0.0023 - val_acc: 0.7827
    Decided to do further experimenting with Adamax optimizer as with the best for simple neural network.
  4. Added 2 more layers: a Convolution2D, a MaxPooling2D. Those layers had the same parameters as layers on step 1 and 2. Got results:
    Epoch 20/1000
    0s - loss: 5.0646e-04 - acc: 0.8347 - val_loss: 0.0015 - val_acc: 0.7734
  5. Added a Dense layer as penultimate. Experimented with 50, 100, 200, 300 neurons. Better results got with 100 neurons:
    Epoch 20/1000
    1s - loss: 4.8141e-04 - acc: 0.8738 - val_loss: 0.0017 - val_acc: 0.7827
  6. Repeated step 4 with adding a Convolution2D and a MaxPooling2D:
    Epoch 39/1000
    1s - loss: 6.5462e-04 - acc: 0.8306 - val_loss: 0.0014 - val_acc: 0.8037
  7. Tuned up hyper parameters for convolutional and max pooling layer. Experimented with filters, kernel sizes, pool sizes. Got better results with 3 couples of convolutional and max pooling layer with 128 filters, 3x3 kernel size and 2x2 pool size for each couple.
    Epoch 26/1000
    5s - loss: 2.8212e-04 - acc: 0.8832 - val_loss: 0.0011 - val_acc: 0.8154
    Adding 4th couple of convolutional and max pooling layer didn’t bring us significant results.
  8. Experimented with adding more Dense layers to the tail of the CNN and number of neurons for them. Better results was with one additional layer Dense with 100 neurons on (3 Dense layers at the end in total).
    Epoch 29/1000
    5s - loss: 2.2877e-04 - acc: 0.9001 - val_loss: 0.0010 - val_acc: 0.8224
  9. Added Dropout layers between fully connected layers to prevent overfitting.
  10. Selected architecture from previous step as main one. Compiled and trained the model with SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam optimizers.

Question 2: Defend your choice of optimizer. Which optimizers did you test, and how did you determine which worked best?

Answer:

I tested SGD, RMSprop, Adagrad, Adadelta, Adam, Adamax, Nadam optimizers in code cells above. Below are graphs with comparison of the optimizers. I was measuring validation loss and validation accuracy for final model to determine which optimizer works the best.

Noticed, that Adamax optimizer gives us highest level of validation accuracy and lowest level of validation loss with minimum number of training epochs.

Epoch 4/1000
3s - loss: 5.8195e-04 - acc: 0.8522 - val_loss: 0.0012 - val_acc: 0.8037

Such way, Adamax optimizer outperforms all the other optimizers.

Use the code cell below to plot the training and validation loss of your neural network. You may find this resource useful.

In [13]:
# Summarize history for acc 
for optimizer_id in history.keys():
    plt.plot(history[optimizer_id].history['acc'])
plt.title('Training Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(history.keys(), loc='upper left')
plt.show()

# Summarize history for val_acc
for optimizer_id in history.keys():
    plt.plot(history[optimizer_id].history['val_acc'])
plt.title('Validation Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(history.keys(), loc='upper left')
plt.show()

# Summarize history for loss
for optimizer_id in history.keys():
    plt.plot(history[optimizer_id].history['loss'])
plt.title('Training Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(history.keys(), loc='upper left')
plt.show()

# Summarize history for val_loss
for optimizer_id in history.keys():
    plt.plot(history[optimizer_id].history['val_loss'])
plt.title('Validation Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(history.keys(), loc='upper left')
plt.show()
In [14]:
# choosed best optimizer
best_optimizer_id = 'adamax'
In [22]:
# Train model with 300 epochs and without callbacks (no EarlyStopping)

compile_train_save_model(best_optimizer_id, epochs=300, callbacks=[])
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 96, 96, 128)       1280      
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 48, 48, 128)       0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 48, 48, 64)        73792     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 24, 24, 64)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 24, 24, 32)        18464     
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 12, 12, 32)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 4608)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 100)               460900    
_________________________________________________________________
dropout_1 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 100)               10100     
_________________________________________________________________
dropout_2 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                3030      
=================================================================
Total params: 567,566
Trainable params: 567,566
Non-trainable params: 0
_________________________________________________________________
Compile, train and save model for adamax
Train on 1712 samples, validate on 428 samples
Epoch 1/300
4s - loss: 6.1135e-04 - acc: 0.8388 - val_loss: 0.0012 - val_acc: 0.8061
Epoch 2/300
3s - loss: 5.3148e-04 - acc: 0.8452 - val_loss: 0.0012 - val_acc: 0.7967
Epoch 3/300
3s - loss: 5.1425e-04 - acc: 0.8575 - val_loss: 0.0012 - val_acc: 0.7850
Epoch 4/300
3s - loss: 5.1530e-04 - acc: 0.8598 - val_loss: 0.0012 - val_acc: 0.7991
Epoch 5/300
3s - loss: 5.1212e-04 - acc: 0.8586 - val_loss: 0.0012 - val_acc: 0.7897
Epoch 6/300
3s - loss: 5.0789e-04 - acc: 0.8505 - val_loss: 0.0012 - val_acc: 0.8131
Epoch 7/300
3s - loss: 5.0544e-04 - acc: 0.8592 - val_loss: 0.0012 - val_acc: 0.7897
Epoch 8/300
4s - loss: 5.1169e-04 - acc: 0.8598 - val_loss: 0.0012 - val_acc: 0.8107
Epoch 9/300
4s - loss: 5.0870e-04 - acc: 0.8627 - val_loss: 0.0012 - val_acc: 0.8107
Epoch 10/300
4s - loss: 5.0639e-04 - acc: 0.8540 - val_loss: 0.0012 - val_acc: 0.7874
Epoch 11/300
4s - loss: 5.0746e-04 - acc: 0.8499 - val_loss: 0.0012 - val_acc: 0.8037
Epoch 12/300
4s - loss: 5.1199e-04 - acc: 0.8522 - val_loss: 0.0012 - val_acc: 0.7897
Epoch 13/300
4s - loss: 5.0721e-04 - acc: 0.8610 - val_loss: 0.0012 - val_acc: 0.7991
Epoch 14/300
4s - loss: 5.0165e-04 - acc: 0.8621 - val_loss: 0.0012 - val_acc: 0.7921
Epoch 15/300
4s - loss: 5.0172e-04 - acc: 0.8592 - val_loss: 0.0012 - val_acc: 0.7850
Epoch 16/300
4s - loss: 5.1582e-04 - acc: 0.8633 - val_loss: 0.0012 - val_acc: 0.7944
Epoch 17/300
4s - loss: 5.0822e-04 - acc: 0.8534 - val_loss: 0.0012 - val_acc: 0.8037
Epoch 18/300
4s - loss: 4.9547e-04 - acc: 0.8651 - val_loss: 0.0012 - val_acc: 0.8084
Epoch 19/300
4s - loss: 5.0119e-04 - acc: 0.8586 - val_loss: 0.0012 - val_acc: 0.7897
Epoch 20/300
4s - loss: 5.0381e-04 - acc: 0.8540 - val_loss: 0.0012 - val_acc: 0.7897
Epoch 21/300
4s - loss: 4.9500e-04 - acc: 0.8621 - val_loss: 0.0012 - val_acc: 0.7991
Epoch 22/300
4s - loss: 4.9770e-04 - acc: 0.8721 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 23/300
4s - loss: 5.0192e-04 - acc: 0.8581 - val_loss: 0.0012 - val_acc: 0.7991
Epoch 24/300
4s - loss: 4.9480e-04 - acc: 0.8692 - val_loss: 0.0012 - val_acc: 0.8061
Epoch 25/300
4s - loss: 4.8411e-04 - acc: 0.8569 - val_loss: 0.0012 - val_acc: 0.8014
Epoch 26/300
4s - loss: 4.9253e-04 - acc: 0.8604 - val_loss: 0.0012 - val_acc: 0.7850
Epoch 27/300
4s - loss: 4.8308e-04 - acc: 0.8639 - val_loss: 0.0012 - val_acc: 0.8014
Epoch 28/300
4s - loss: 4.9161e-04 - acc: 0.8651 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 29/300
4s - loss: 4.8641e-04 - acc: 0.8686 - val_loss: 0.0013 - val_acc: 0.8037
Epoch 30/300
4s - loss: 4.8052e-04 - acc: 0.8627 - val_loss: 0.0012 - val_acc: 0.7991
Epoch 31/300
4s - loss: 4.7875e-04 - acc: 0.8680 - val_loss: 0.0012 - val_acc: 0.7921
Epoch 32/300
4s - loss: 4.7938e-04 - acc: 0.8709 - val_loss: 0.0012 - val_acc: 0.7991
Epoch 33/300
4s - loss: 4.8254e-04 - acc: 0.8668 - val_loss: 0.0012 - val_acc: 0.7804
Epoch 34/300
4s - loss: 4.7731e-04 - acc: 0.8645 - val_loss: 0.0012 - val_acc: 0.7897
Epoch 35/300
4s - loss: 4.7651e-04 - acc: 0.8563 - val_loss: 0.0012 - val_acc: 0.8154
Epoch 36/300
4s - loss: 4.8415e-04 - acc: 0.8838 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 37/300
4s - loss: 4.6785e-04 - acc: 0.8586 - val_loss: 0.0012 - val_acc: 0.7921
Epoch 38/300
4s - loss: 4.7971e-04 - acc: 0.8581 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 39/300
4s - loss: 4.7329e-04 - acc: 0.8651 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 40/300
4s - loss: 4.7810e-04 - acc: 0.8721 - val_loss: 0.0012 - val_acc: 0.7944
Epoch 41/300
4s - loss: 4.8025e-04 - acc: 0.8686 - val_loss: 0.0012 - val_acc: 0.7991
Epoch 42/300
4s - loss: 4.6098e-04 - acc: 0.8692 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 43/300
4s - loss: 4.6598e-04 - acc: 0.8651 - val_loss: 0.0012 - val_acc: 0.7967
Epoch 44/300
4s - loss: 4.6527e-04 - acc: 0.8662 - val_loss: 0.0012 - val_acc: 0.7850
Epoch 45/300
3s - loss: 4.6154e-04 - acc: 0.8627 - val_loss: 0.0012 - val_acc: 0.7944
Epoch 46/300
4s - loss: 4.7765e-04 - acc: 0.8651 - val_loss: 0.0012 - val_acc: 0.8061
Epoch 47/300
4s - loss: 4.6642e-04 - acc: 0.8709 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 48/300
4s - loss: 4.6926e-04 - acc: 0.8668 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 49/300
4s - loss: 4.6394e-04 - acc: 0.8621 - val_loss: 0.0012 - val_acc: 0.8037
Epoch 50/300
4s - loss: 4.7087e-04 - acc: 0.8797 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 51/300
4s - loss: 4.7223e-04 - acc: 0.8610 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 52/300
4s - loss: 4.6008e-04 - acc: 0.8727 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 53/300
4s - loss: 4.6118e-04 - acc: 0.8592 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 54/300
4s - loss: 4.6052e-04 - acc: 0.8738 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 55/300
4s - loss: 4.5820e-04 - acc: 0.8768 - val_loss: 0.0012 - val_acc: 0.7944
Epoch 56/300
4s - loss: 4.6442e-04 - acc: 0.8715 - val_loss: 0.0012 - val_acc: 0.7991
Epoch 57/300
4s - loss: 4.5414e-04 - acc: 0.8732 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 58/300
4s - loss: 4.5306e-04 - acc: 0.8604 - val_loss: 0.0012 - val_acc: 0.8084
Epoch 59/300
4s - loss: 4.4433e-04 - acc: 0.8715 - val_loss: 0.0012 - val_acc: 0.7944
Epoch 60/300
4s - loss: 4.5298e-04 - acc: 0.8651 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 61/300
4s - loss: 4.4625e-04 - acc: 0.8762 - val_loss: 0.0012 - val_acc: 0.7804
Epoch 62/300
4s - loss: 4.5953e-04 - acc: 0.8697 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 63/300
4s - loss: 4.5480e-04 - acc: 0.8703 - val_loss: 0.0012 - val_acc: 0.7827
Epoch 64/300
4s - loss: 4.6210e-04 - acc: 0.8703 - val_loss: 0.0012 - val_acc: 0.7967
Epoch 65/300
4s - loss: 4.4713e-04 - acc: 0.8738 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 66/300
4s - loss: 4.5874e-04 - acc: 0.8738 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 67/300
4s - loss: 4.6311e-04 - acc: 0.8657 - val_loss: 0.0012 - val_acc: 0.7944
Epoch 68/300
4s - loss: 4.5140e-04 - acc: 0.8657 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 69/300
4s - loss: 4.5333e-04 - acc: 0.8633 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 70/300
4s - loss: 4.5642e-04 - acc: 0.8797 - val_loss: 0.0012 - val_acc: 0.8014
Epoch 71/300
4s - loss: 4.4865e-04 - acc: 0.8703 - val_loss: 0.0012 - val_acc: 0.8061
Epoch 72/300
4s - loss: 4.4137e-04 - acc: 0.8598 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 73/300
4s - loss: 4.5298e-04 - acc: 0.8651 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 74/300
4s - loss: 4.4930e-04 - acc: 0.8727 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 75/300
4s - loss: 4.5701e-04 - acc: 0.8692 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 76/300
4s - loss: 4.3777e-04 - acc: 0.8820 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 77/300
4s - loss: 4.4964e-04 - acc: 0.8808 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 78/300
4s - loss: 4.5481e-04 - acc: 0.8627 - val_loss: 0.0013 - val_acc: 0.8061
Epoch 79/300
3s - loss: 4.4978e-04 - acc: 0.8598 - val_loss: 0.0013 - val_acc: 0.8131
Epoch 80/300
4s - loss: 4.4928e-04 - acc: 0.8721 - val_loss: 0.0013 - val_acc: 0.8061
Epoch 81/300
4s - loss: 4.4078e-04 - acc: 0.8820 - val_loss: 0.0012 - val_acc: 0.8037
Epoch 82/300
4s - loss: 4.4834e-04 - acc: 0.8575 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 83/300
4s - loss: 4.5011e-04 - acc: 0.8721 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 84/300
4s - loss: 4.4841e-04 - acc: 0.8727 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 85/300
4s - loss: 4.3891e-04 - acc: 0.8785 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 86/300
4s - loss: 4.4693e-04 - acc: 0.8697 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 87/300
3s - loss: 4.4042e-04 - acc: 0.8715 - val_loss: 0.0013 - val_acc: 0.8084
Epoch 88/300
3s - loss: 4.3793e-04 - acc: 0.8750 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 89/300
3s - loss: 4.3728e-04 - acc: 0.8738 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 90/300
4s - loss: 4.3845e-04 - acc: 0.8797 - val_loss: 0.0013 - val_acc: 0.8037
Epoch 91/300
4s - loss: 4.4287e-04 - acc: 0.8791 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 92/300
3s - loss: 4.4851e-04 - acc: 0.8692 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 93/300
4s - loss: 4.3481e-04 - acc: 0.8674 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 94/300
4s - loss: 4.4254e-04 - acc: 0.8832 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 95/300
3s - loss: 4.4333e-04 - acc: 0.8732 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 96/300
3s - loss: 4.4021e-04 - acc: 0.8645 - val_loss: 0.0012 - val_acc: 0.8107
Epoch 97/300
4s - loss: 4.2727e-04 - acc: 0.8703 - val_loss: 0.0013 - val_acc: 0.8037
Epoch 98/300
4s - loss: 4.3651e-04 - acc: 0.8768 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 99/300
3s - loss: 4.3338e-04 - acc: 0.8744 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 100/300
3s - loss: 4.3510e-04 - acc: 0.8703 - val_loss: 0.0012 - val_acc: 0.7991
Epoch 101/300
3s - loss: 4.3049e-04 - acc: 0.8732 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 102/300
3s - loss: 4.2664e-04 - acc: 0.8750 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 103/300
4s - loss: 4.3492e-04 - acc: 0.8768 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 104/300
3s - loss: 4.2969e-04 - acc: 0.8814 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 105/300
4s - loss: 4.2719e-04 - acc: 0.8738 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 106/300
4s - loss: 4.2888e-04 - acc: 0.8721 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 107/300
4s - loss: 4.2876e-04 - acc: 0.8873 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 108/300
4s - loss: 4.3898e-04 - acc: 0.8604 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 109/300
4s - loss: 4.2881e-04 - acc: 0.8849 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 110/300
4s - loss: 4.2240e-04 - acc: 0.8855 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 111/300
4s - loss: 4.3596e-04 - acc: 0.8744 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 112/300
4s - loss: 4.3954e-04 - acc: 0.8668 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 113/300
4s - loss: 4.3625e-04 - acc: 0.8703 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 114/300
4s - loss: 4.4007e-04 - acc: 0.8686 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 115/300
4s - loss: 4.2658e-04 - acc: 0.8645 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 116/300
4s - loss: 4.2748e-04 - acc: 0.8768 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 117/300
4s - loss: 4.3412e-04 - acc: 0.8703 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 118/300
4s - loss: 4.1718e-04 - acc: 0.8627 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 119/300
4s - loss: 4.2682e-04 - acc: 0.8768 - val_loss: 0.0012 - val_acc: 0.7921
Epoch 120/300
4s - loss: 4.2238e-04 - acc: 0.8744 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 121/300
4s - loss: 4.1386e-04 - acc: 0.8803 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 122/300
4s - loss: 4.2244e-04 - acc: 0.8762 - val_loss: 0.0013 - val_acc: 0.8061
Epoch 123/300
4s - loss: 4.2206e-04 - acc: 0.8879 - val_loss: 0.0012 - val_acc: 0.7874
Epoch 124/300
4s - loss: 4.2122e-04 - acc: 0.8703 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 125/300
4s - loss: 4.2183e-04 - acc: 0.8820 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 126/300
4s - loss: 4.2060e-04 - acc: 0.8791 - val_loss: 0.0013 - val_acc: 0.7734
Epoch 127/300
4s - loss: 4.2046e-04 - acc: 0.8803 - val_loss: 0.0013 - val_acc: 0.8037
Epoch 128/300
3s - loss: 4.2947e-04 - acc: 0.8814 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 129/300
4s - loss: 4.2365e-04 - acc: 0.8843 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 130/300
4s - loss: 4.1881e-04 - acc: 0.8738 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 131/300
3s - loss: 4.1513e-04 - acc: 0.8820 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 132/300
4s - loss: 4.2671e-04 - acc: 0.8709 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 133/300
4s - loss: 4.2536e-04 - acc: 0.8814 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 134/300
3s - loss: 4.1462e-04 - acc: 0.8756 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 135/300
4s - loss: 4.2889e-04 - acc: 0.8668 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 136/300
3s - loss: 4.2666e-04 - acc: 0.8744 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 137/300
4s - loss: 4.3611e-04 - acc: 0.8779 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 138/300
4s - loss: 4.2120e-04 - acc: 0.8738 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 139/300
4s - loss: 4.2297e-04 - acc: 0.8791 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 140/300
3s - loss: 4.2027e-04 - acc: 0.8727 - val_loss: 0.0013 - val_acc: 0.7710
Epoch 141/300
3s - loss: 4.0645e-04 - acc: 0.8756 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 142/300
3s - loss: 4.1222e-04 - acc: 0.8797 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 143/300
4s - loss: 4.2417e-04 - acc: 0.8575 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 144/300
4s - loss: 4.2044e-04 - acc: 0.8674 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 145/300
4s - loss: 4.1667e-04 - acc: 0.8592 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 146/300
4s - loss: 4.1674e-04 - acc: 0.8873 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 147/300
4s - loss: 4.2669e-04 - acc: 0.8657 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 148/300
4s - loss: 4.1845e-04 - acc: 0.8832 - val_loss: 0.0013 - val_acc: 0.8037
Epoch 149/300
3s - loss: 4.1334e-04 - acc: 0.8820 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 150/300
3s - loss: 4.0948e-04 - acc: 0.8803 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 151/300
3s - loss: 4.1087e-04 - acc: 0.8768 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 152/300
4s - loss: 4.1972e-04 - acc: 0.8820 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 153/300
3s - loss: 4.1154e-04 - acc: 0.8680 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 154/300
4s - loss: 4.1305e-04 - acc: 0.8756 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 155/300
3s - loss: 4.0915e-04 - acc: 0.8773 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 156/300
3s - loss: 4.2229e-04 - acc: 0.8709 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 157/300
4s - loss: 4.0897e-04 - acc: 0.8534 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 158/300
3s - loss: 4.3467e-04 - acc: 0.8826 - val_loss: 0.0013 - val_acc: 0.8084
Epoch 159/300
3s - loss: 4.1315e-04 - acc: 0.8925 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 160/300
3s - loss: 4.0715e-04 - acc: 0.8738 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 161/300
3s - loss: 4.1463e-04 - acc: 0.8592 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 162/300
3s - loss: 4.0718e-04 - acc: 0.8931 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 163/300
4s - loss: 4.1372e-04 - acc: 0.8762 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 164/300
3s - loss: 4.1290e-04 - acc: 0.8744 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 165/300
3s - loss: 3.9962e-04 - acc: 0.9001 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 166/300
4s - loss: 4.1078e-04 - acc: 0.8843 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 167/300
4s - loss: 4.0346e-04 - acc: 0.8651 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 168/300
3s - loss: 4.1832e-04 - acc: 0.8879 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 169/300
4s - loss: 4.1230e-04 - acc: 0.8826 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 170/300
3s - loss: 3.9902e-04 - acc: 0.8703 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 171/300
3s - loss: 4.1430e-04 - acc: 0.8627 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 172/300
3s - loss: 4.0959e-04 - acc: 0.8709 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 173/300
4s - loss: 4.0825e-04 - acc: 0.8756 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 174/300
4s - loss: 4.0453e-04 - acc: 0.8750 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 175/300
4s - loss: 4.0675e-04 - acc: 0.8797 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 176/300
3s - loss: 4.0105e-04 - acc: 0.8873 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 177/300
4s - loss: 4.1437e-04 - acc: 0.8919 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 178/300
3s - loss: 4.1987e-04 - acc: 0.8814 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 179/300
3s - loss: 4.0497e-04 - acc: 0.8721 - val_loss: 0.0013 - val_acc: 0.7687
Epoch 180/300
3s - loss: 4.0571e-04 - acc: 0.8768 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 181/300
3s - loss: 4.0113e-04 - acc: 0.8750 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 182/300
3s - loss: 4.0555e-04 - acc: 0.8779 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 183/300
3s - loss: 4.1267e-04 - acc: 0.8756 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 184/300
4s - loss: 4.0823e-04 - acc: 0.8762 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 185/300
4s - loss: 4.1014e-04 - acc: 0.8692 - val_loss: 0.0013 - val_acc: 0.7664
Epoch 186/300
4s - loss: 4.0232e-04 - acc: 0.8715 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 187/300
3s - loss: 4.0756e-04 - acc: 0.8791 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 188/300
4s - loss: 4.0137e-04 - acc: 0.8768 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 189/300
4s - loss: 4.1021e-04 - acc: 0.8773 - val_loss: 0.0013 - val_acc: 0.7734
Epoch 190/300
3s - loss: 4.1163e-04 - acc: 0.8908 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 191/300
3s - loss: 4.1305e-04 - acc: 0.8732 - val_loss: 0.0013 - val_acc: 0.8037
Epoch 192/300
3s - loss: 4.0180e-04 - acc: 0.8709 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 193/300
3s - loss: 4.0606e-04 - acc: 0.8768 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 194/300
3s - loss: 4.0701e-04 - acc: 0.8645 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 195/300
4s - loss: 4.0353e-04 - acc: 0.8657 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 196/300
4s - loss: 4.0290e-04 - acc: 0.8838 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 197/300
3s - loss: 3.9792e-04 - acc: 0.8779 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 198/300
3s - loss: 4.0054e-04 - acc: 0.8785 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 199/300
4s - loss: 4.0327e-04 - acc: 0.8703 - val_loss: 0.0013 - val_acc: 0.7757
Epoch 200/300
3s - loss: 4.0253e-04 - acc: 0.8797 - val_loss: 0.0013 - val_acc: 0.7757
Epoch 201/300
4s - loss: 4.0289e-04 - acc: 0.8768 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 202/300
4s - loss: 4.0301e-04 - acc: 0.8768 - val_loss: 0.0013 - val_acc: 0.7734
Epoch 203/300
3s - loss: 4.0619e-04 - acc: 0.8732 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 204/300
3s - loss: 3.9869e-04 - acc: 0.8867 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 205/300
4s - loss: 4.0643e-04 - acc: 0.8820 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 206/300
3s - loss: 4.0239e-04 - acc: 0.8715 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 207/300
4s - loss: 4.0572e-04 - acc: 0.8762 - val_loss: 0.0013 - val_acc: 0.7710
Epoch 208/300
3s - loss: 4.0945e-04 - acc: 0.8709 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 209/300
4s - loss: 4.0318e-04 - acc: 0.8832 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 210/300
3s - loss: 4.0341e-04 - acc: 0.8721 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 211/300
3s - loss: 3.9796e-04 - acc: 0.8721 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 212/300
4s - loss: 3.9625e-04 - acc: 0.8773 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 213/300
3s - loss: 3.9992e-04 - acc: 0.8867 - val_loss: 0.0013 - val_acc: 0.8061
Epoch 214/300
4s - loss: 4.0900e-04 - acc: 0.8773 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 215/300
4s - loss: 4.0255e-04 - acc: 0.8884 - val_loss: 0.0013 - val_acc: 0.7757
Epoch 216/300
3s - loss: 3.8356e-04 - acc: 0.8768 - val_loss: 0.0013 - val_acc: 0.8061
Epoch 217/300
3s - loss: 3.9590e-04 - acc: 0.8791 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 218/300
4s - loss: 3.9549e-04 - acc: 0.8867 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 219/300
4s - loss: 3.9887e-04 - acc: 0.8820 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 220/300
4s - loss: 3.8713e-04 - acc: 0.8937 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 221/300
4s - loss: 4.0645e-04 - acc: 0.8756 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 222/300
4s - loss: 4.0542e-04 - acc: 0.8657 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 223/300
4s - loss: 4.0054e-04 - acc: 0.8773 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 224/300
4s - loss: 4.0320e-04 - acc: 0.8826 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 225/300
4s - loss: 4.0393e-04 - acc: 0.8849 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 226/300
4s - loss: 4.0733e-04 - acc: 0.8779 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 227/300
4s - loss: 4.0295e-04 - acc: 0.8680 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 228/300
4s - loss: 4.0141e-04 - acc: 0.8803 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 229/300
4s - loss: 4.0087e-04 - acc: 0.8797 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 230/300
4s - loss: 4.0341e-04 - acc: 0.8610 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 231/300
4s - loss: 3.8786e-04 - acc: 0.8785 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 232/300
4s - loss: 3.8799e-04 - acc: 0.8762 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 233/300
4s - loss: 4.1522e-04 - acc: 0.8803 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 234/300
4s - loss: 4.0566e-04 - acc: 0.8762 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 235/300
4s - loss: 4.0640e-04 - acc: 0.8762 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 236/300
4s - loss: 3.8622e-04 - acc: 0.8808 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 237/300
4s - loss: 4.0078e-04 - acc: 0.8820 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 238/300
4s - loss: 4.0083e-04 - acc: 0.8820 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 239/300
4s - loss: 4.0387e-04 - acc: 0.8820 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 240/300
3s - loss: 3.9895e-04 - acc: 0.8709 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 241/300
4s - loss: 3.9776e-04 - acc: 0.8814 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 242/300
3s - loss: 4.0830e-04 - acc: 0.8715 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 243/300
3s - loss: 3.9726e-04 - acc: 0.8768 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 244/300
4s - loss: 3.8865e-04 - acc: 0.8902 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 245/300
4s - loss: 3.9682e-04 - acc: 0.8750 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 246/300
4s - loss: 3.9796e-04 - acc: 0.8732 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 247/300
3s - loss: 3.9444e-04 - acc: 0.8873 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 248/300
4s - loss: 3.9559e-04 - acc: 0.8657 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 249/300
3s - loss: 3.9734e-04 - acc: 0.8797 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 250/300
3s - loss: 4.0744e-04 - acc: 0.8791 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 251/300
4s - loss: 3.9462e-04 - acc: 0.8762 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 252/300
3s - loss: 3.9153e-04 - acc: 0.8703 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 253/300
4s - loss: 3.9733e-04 - acc: 0.8703 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 254/300
4s - loss: 3.9658e-04 - acc: 0.8785 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 255/300
3s - loss: 3.8155e-04 - acc: 0.8785 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 256/300
4s - loss: 3.9170e-04 - acc: 0.8832 - val_loss: 0.0013 - val_acc: 0.7967
Epoch 257/300
4s - loss: 3.9701e-04 - acc: 0.8709 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 258/300
3s - loss: 3.8991e-04 - acc: 0.8773 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 259/300
4s - loss: 3.9581e-04 - acc: 0.8762 - val_loss: 0.0013 - val_acc: 0.7734
Epoch 260/300
4s - loss: 3.9700e-04 - acc: 0.8803 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 261/300
4s - loss: 3.9281e-04 - acc: 0.8727 - val_loss: 0.0013 - val_acc: 0.7757
Epoch 262/300
4s - loss: 3.9098e-04 - acc: 0.8662 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 263/300
4s - loss: 3.8584e-04 - acc: 0.8843 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 264/300
4s - loss: 3.9252e-04 - acc: 0.8791 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 265/300
4s - loss: 3.8773e-04 - acc: 0.8727 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 266/300
4s - loss: 3.8951e-04 - acc: 0.8791 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 267/300
3s - loss: 3.8859e-04 - acc: 0.8791 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 268/300
3s - loss: 3.9287e-04 - acc: 0.8814 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 269/300
4s - loss: 3.9308e-04 - acc: 0.8843 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 270/300
3s - loss: 3.8978e-04 - acc: 0.8838 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 271/300
3s - loss: 3.9296e-04 - acc: 0.8949 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 272/300
3s - loss: 3.9510e-04 - acc: 0.8727 - val_loss: 0.0013 - val_acc: 0.7734
Epoch 273/300
3s - loss: 3.9109e-04 - acc: 0.8803 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 274/300
4s - loss: 4.0171e-04 - acc: 0.8843 - val_loss: 0.0013 - val_acc: 0.7757
Epoch 275/300
4s - loss: 3.9296e-04 - acc: 0.8808 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 276/300
4s - loss: 3.7993e-04 - acc: 0.8814 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 277/300
3s - loss: 3.9338e-04 - acc: 0.8744 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 278/300
4s - loss: 3.8005e-04 - acc: 0.8826 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 279/300
4s - loss: 3.9021e-04 - acc: 0.8867 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 280/300
3s - loss: 3.8629e-04 - acc: 0.8849 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 281/300
3s - loss: 3.9494e-04 - acc: 0.8896 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 282/300
3s - loss: 3.9884e-04 - acc: 0.8832 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 283/300
4s - loss: 3.9251e-04 - acc: 0.8873 - val_loss: 0.0013 - val_acc: 0.7734
Epoch 284/300
3s - loss: 3.9164e-04 - acc: 0.8750 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 285/300
4s - loss: 3.9553e-04 - acc: 0.8762 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 286/300
4s - loss: 3.8075e-04 - acc: 0.8931 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 287/300
4s - loss: 3.9116e-04 - acc: 0.8855 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 288/300
4s - loss: 3.8988e-04 - acc: 0.8756 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 289/300
4s - loss: 3.8983e-04 - acc: 0.8820 - val_loss: 0.0013 - val_acc: 0.7757
Epoch 290/300
3s - loss: 3.9271e-04 - acc: 0.8826 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 291/300
3s - loss: 3.9359e-04 - acc: 0.8791 - val_loss: 0.0013 - val_acc: 0.7734
Epoch 292/300
3s - loss: 3.9231e-04 - acc: 0.8803 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 293/300
3s - loss: 3.9291e-04 - acc: 0.8849 - val_loss: 0.0013 - val_acc: 0.8014
Epoch 294/300
3s - loss: 3.8683e-04 - acc: 0.8785 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 295/300
3s - loss: 3.8963e-04 - acc: 0.8785 - val_loss: 0.0013 - val_acc: 0.7897
Epoch 296/300
3s - loss: 3.9436e-04 - acc: 0.8738 - val_loss: 0.0013 - val_acc: 0.7991
Epoch 297/300
4s - loss: 3.9172e-04 - acc: 0.8832 - val_loss: 0.0013 - val_acc: 0.7780
Epoch 298/300
4s - loss: 4.0369e-04 - acc: 0.8779 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 299/300
4s - loss: 3.8785e-04 - acc: 0.8855 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 300/300
4s - loss: 3.8491e-04 - acc: 0.8750 - val_loss: 0.0013 - val_acc: 0.7944
In [23]:
## DONE: Visualize the training and validation loss of your neural network

# List all data in history
print('history keys:', history[best_optimizer_id].history.keys())

# Summarize history for accuracy
plt.plot(history[best_optimizer_id].history['acc'])
plt.plot(history[best_optimizer_id].history['val_acc'])
plt.title('Training and Validation Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()

# Summarize history for loss
plt.plot(history[best_optimizer_id].history['loss'])
plt.plot(history[best_optimizer_id].history['val_loss'])
plt.title('Training and Validation Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()
history keys: dict_keys(['loss', 'val_loss', 'val_acc', 'acc'])

Question 3: Do you notice any evidence of overfitting or underfitting in the above plot? If so, what steps have you taken to improve your model? Note that slight overfitting or underfitting will not hurt your chances of a successful submission, as long as you have attempted some solutions towards improving your model (such as regularization, dropout, increased/decreased number of layers, etc).

Answer:

Above, I trained the CNN with Adamax optimizer on 300 epochs. I plotted the training and validation accuracy and loss. As we can see, there is some overfitting

To prevent overfitting I used the following regularizaton strategies:

  • I added 2 Dropout layers between fully connected layers.
  • As we see on plot above, overfitting starts after 250 epochs. We could stop training on 250 epochs. But, in my opinion, EarlyStopping method works easier and better.
  • Used EarlyStopping callback to stop training when a monitored val_loss quantity has stopped improving.
In [24]:
# Retrain model with EarlyStopping callback again

compile_train_save_model(best_optimizer_id)
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 96, 96, 128)       1280      
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 48, 48, 128)       0         
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 48, 48, 64)        73792     
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 24, 24, 64)        0         
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 24, 24, 32)        18464     
_________________________________________________________________
max_pooling2d_3 (MaxPooling2 (None, 12, 12, 32)        0         
_________________________________________________________________
flatten_1 (Flatten)          (None, 4608)              0         
_________________________________________________________________
dense_1 (Dense)              (None, 100)               460900    
_________________________________________________________________
dropout_1 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_2 (Dense)              (None, 100)               10100     
_________________________________________________________________
dropout_2 (Dropout)          (None, 100)               0         
_________________________________________________________________
dense_3 (Dense)              (None, 30)                3030      
=================================================================
Total params: 567,566
Trainable params: 567,566
Non-trainable params: 0
_________________________________________________________________
Compile, train and save model for adamax
Train on 1712 samples, validate on 428 samples
Epoch 1/300
4s - loss: 4.0452e-04 - acc: 0.8732 - val_loss: 0.0013 - val_acc: 0.7850
Epoch 2/300
4s - loss: 4.0758e-04 - acc: 0.8738 - val_loss: 0.0013 - val_acc: 0.7921
Epoch 3/300
4s - loss: 3.9488e-04 - acc: 0.8709 - val_loss: 0.0013 - val_acc: 0.7944
Epoch 4/300
4s - loss: 3.9260e-04 - acc: 0.8797 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 5/300
4s - loss: 3.7485e-04 - acc: 0.8750 - val_loss: 0.0013 - val_acc: 0.7827
Epoch 6/300
4s - loss: 3.9487e-04 - acc: 0.8843 - val_loss: 0.0013 - val_acc: 0.7804
Epoch 7/300
4s - loss: 3.8663e-04 - acc: 0.8756 - val_loss: 0.0013 - val_acc: 0.7757
Epoch 8/300
4s - loss: 3.8883e-04 - acc: 0.8902 - val_loss: 0.0013 - val_acc: 0.7874
Epoch 00007: early stopping
In [25]:
## DONE: Visualize the training and validation loss of your neural network

# List all data in history
print('history keys:', history[best_optimizer_id].history.keys())

# Summarize history for accuracy
plt.plot(history[best_optimizer_id].history['acc'])
plt.plot(history[best_optimizer_id].history['val_acc'])
plt.title('Training and Validation Accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()

# Summarize history for loss
plt.plot(history[best_optimizer_id].history['loss'])
plt.plot(history[best_optimizer_id].history['val_loss'])
plt.title('Training and Validation Loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()
history keys: dict_keys(['loss', 'val_loss', 'val_acc', 'acc'])

Visualize a Subset of the Test Predictions

Execute the code cell below to visualize your model's predicted keypoints on a subset of the testing images.

In [16]:
y_test = model.predict(X_test)
fig = plt.figure(figsize=(20,20))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)
for i in range(9):
    ax = fig.add_subplot(3, 3, i + 1, xticks=[], yticks=[])
    plot_data(X_test[i], y_test[i], ax)

Step 8: Complete the pipeline

With the work you did in Sections 1 and 2 of this notebook, along with your freshly trained facial keypoint detector, you can now complete the full pipeline. That is given a color image containing a person or persons you can now

  • Detect the faces in this image automatically using OpenCV
  • Predict the facial keypoints in each face detected in the image
  • Paint predicted keypoints on each face detected

In this Subsection you will do just this!

(IMPLEMENTATION) Facial Keypoints Detector

Use the OpenCV face detection functionality you built in previous Sections to expand the functionality of your keypoints detector to color images with arbitrary size. Your function should perform the following steps

  1. Accept a color image.
  2. Convert the image to grayscale.
  3. Detect and crop the face contained in the image.
  4. Locate the facial keypoints in the cropped image.
  5. Overlay the facial keypoints in the original (color, uncropped) image.

Note: step 4 can be the trickiest because remember your convolutional network is only trained to detect facial keypoints in $96 \times 96$ grayscale images where each pixel was normalized to lie in the interval $[0,1]$, and remember that each facial keypoint was normalized during training to the interval $[-1,1]$. This means - practically speaking - to paint detected keypoints onto a test face you need to perform this same pre-processing to your candidate face - that is after detecting it you should resize it to $96 \times 96$ and normalize its values before feeding it into your facial keypoint detector. To be shown correctly on the original image the output keypoints from your detector then need to be shifted and re-normalized from the interval $[-1,1]$ to the width and height of your detected face.

When complete you should be able to produce example images like the one below

In [140]:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')


# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

image_copy = np.copy(image)

# plot our image
fig = plt.figure(figsize = (9,9))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('image copy')
ax1.imshow(image_copy)
Out[140]:
<matplotlib.image.AxesImage at 0x183a6bcef0>
In [17]:
### DONE: Use the face detection code we saw in Section 1 with your trained conv-net 
## DONE: Paint the predicted keypoints on the test image

model_path = 'my_model_{}.h5'.format(best_optimizer_id)

img_path = 'images/obamas4.jpg' 
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')

model = load_model(model_path)
img = cv2.imread(img_path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
fig = plt.figure(figsize=(9,9))
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[])
ax.imshow(cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB))

plt.title('Image with Facial Keypoints')
for (x,y,w,h) in faces:
    rectangle = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
    ax.imshow(cv2.cvtColor(rectangle, cv2.COLOR_BGR2RGB))

    bgr_crop = img[y:y+h, x:x+w] 
    orig_shape_crop = bgr_crop.shape
    gray_crop = cv2.cvtColor(bgr_crop, cv2.COLOR_BGR2GRAY)
    resize_gray_crop = cv2.resize(gray_crop, (96, 96)) / 255.
    landmarks = np.squeeze(model.predict(
        np.expand_dims(np.expand_dims(resize_gray_crop, axis=-1), axis=0)))
    ax.scatter(((landmarks[0::2] * 48 + 48) * orig_shape_crop[0] / 96) + x, 
               ((landmarks[1::2] * 48 + 48) * orig_shape_crop[1] / 96) + y, 
               marker='o', c='g', s=20)

plt.show()

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add facial keypoint detection to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for keypoint detection and marking in the previous exercise and you should be good to go!

In [3]:
import cv2
import time
import numpy as np
from keras.models import load_model

model_path = 'my_model_{}.h5'.format(best_optimizer_id)

face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
model = load_model(model_path)

def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # Try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # keep video stream open
    while rval:
        # plot image from camera with detections marked
        
        gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.25, 6)
        for (x, y, w, h) in faces:
            gray_crop = gray[y:y+h, x:x+w] 
            orig_shape_crop = gray_crop.shape
            resize_gray_crop = cv2.resize(gray_crop, (96, 96)) / 255.
            landmarks = np.squeeze(model.predict(np.expand_dims(np.expand_dims(resize_gray_crop, axis=-1), axis=0)))
            for (lx, ly) in zip(landmarks[0::2], landmarks[1::2]):
                lx = int(((lx + 1) * 48 * orig_shape_crop[0] / 96) + x)
                ly = int(((ly + 1) * 48 * orig_shape_crop[1] / 96) + y)
                cv2.circle(frame, (lx, ly), 3, (0, 255, 0), -1)
            cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 0, 255), 2)
            
        cv2.imshow("face detection activated", frame)
       
        # exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # exit by pressing any key
            # destroy windows
            cv2.destroyAllWindows()
            
            # hack from stack overflow for making sure window closes on osx --> https://stackoverflow.com/questions/6116564/destroywindow-does-not-close-window-on-mac-using-python-and-opencv
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()  
In [ ]:
# Run your keypoint face painter
laptop_camera_go()

(Optional) Further Directions - add a filter using facial keypoints

Using your freshly minted facial keypoint detector pipeline you can now do things like add fun filters to a person's face automatically. In this optional exercise you can play around with adding sunglasses automatically to each individual's face in an image as shown in a demonstration image below.

To produce this effect an image of a pair of sunglasses shown in the Python cell below.

In [5]:
# Load in sunglasses image - note the usage of the special option
# cv2.IMREAD_UNCHANGED, this option is used because the sunglasses 
# image has a 4th channel that allows us to control how transparent each pixel in the image is
sunglasses = cv2.imread("images/sunglasses_4.png", cv2.IMREAD_UNCHANGED)

# Plot the image
fig = plt.figure(figsize = (6,6))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.imshow(sunglasses)
ax1.axis('off');

This image is placed over each individual's face using the detected eye points to determine the location of the sunglasses, and eyebrow points to determine the size that the sunglasses should be for each person (one could also use the nose point to determine this).

Notice that this image actually has 4 channels, not just 3.

In [6]:
# Print out the shape of the sunglasses image
print ('The sunglasses image has shape: ' + str(np.shape(sunglasses)))
The sunglasses image has shape: (1123, 3064, 4)

It has the usual red, blue, and green channels any color image has, with the 4th channel representing the transparency level of each pixel in the image. Here's how the transparency channel works: the lower the value, the more transparent the pixel will become. The lower bound (completely transparent) is zero here, so any pixels set to 0 will not be seen.

This is how we can place this image of sunglasses on someone's face and still see the area around of their face where the sunglasses lie - because these pixels in the sunglasses image have been made completely transparent.

Lets check out the alpha channel of our sunglasses image in the next Python cell. Note because many of the pixels near the boundary are transparent we'll need to explicitly print out non-zero values if we want to see them.

In [54]:
# Print out the sunglasses transparency (alpha) channel
alpha_channel = sunglasses[:,:,3]
print ('the alpha channel here looks like')
print (alpha_channel)

# Just to double check that there are indeed non-zero values
# Let's find and print out every value greater than zero
values = np.where(alpha_channel != 0)
print ('\n the non-zero values of the alpha channel look like')
print (values)

print('\nmax value in alpha_channel:', alpha_channel.max())
the alpha channel here looks like
[[0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 ..., 
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]
 [0 0 0 ..., 0 0 0]]

 the non-zero values of the alpha channel look like
(array([  17,   17,   17, ..., 1109, 1109, 1109]), array([ 687,  688,  689, ..., 2376, 2377, 2378]))

max value in alpha_channel: 255

This means that when we place this sunglasses image on top of another image, we can use the transparency channel as a filter to tell us which pixels to overlay on a new image (only the non-transparent ones with values greater than zero).

One last thing: it's helpful to understand which keypoint belongs to the eyes, mouth, etc. So, in the image below, we also display the index of each facial keypoint directly on the image so that you can tell which keypoints are for the eyes, eyebrows, etc.

With this information, you're well on your way to completing this filtering task! See if you can place the sunglasses automatically on the individuals in the image loaded in / shown in the next Python cell.

In [8]:
# Load in color image for face detection
image = cv2.imread('images/obamas4.jpg')

# Convert the image to RGB colorspace
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)


# Plot the image
fig = plt.figure(figsize = (8,8))
ax1 = fig.add_subplot(111)
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('Original Image')
ax1.imshow(image)
Out[8]:
<matplotlib.image.AxesImage at 0x1165529b0>
In [18]:
## (Optional) DONE: Use the face detection code we saw in Section 1 with your trained conv-net to put
## sunglasses on the individuals in our test image

model_path = 'my_model_{}.h5'.format(best_optimizer_id)

img_path = 'images/obamas4.jpg' 
face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
sunglasses = cv2.imread("images/sunglasses_4.png", cv2.IMREAD_UNCHANGED)

model = load_model(model_path)
img = cv2.imread(img_path)
rgb_img = cv2.cvtColor(cv2.imread(img_path), cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray)
fig = plt.figure(figsize=(9,9))
ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[])

plt.title('Image with Facial Keypoints')
for (x,y,w,h) in faces:
    rectangle = cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
    ax.imshow(cv2.cvtColor(rectangle, cv2.COLOR_BGR2RGB))

    bgr_crop = img[y:y+h, x:x+w] 
    orig_shape_crop = bgr_crop.shape
    gray_crop = cv2.cvtColor(bgr_crop, cv2.COLOR_BGR2GRAY)
    resize_gray_crop = cv2.resize(gray_crop, (96, 96)) / 255.
    landmarks = np.squeeze(model.predict(
        np.expand_dims(np.expand_dims(resize_gray_crop, axis=-1), axis=0)))
    
    sg_l_x = int(((landmarks[18] * 48 + 48) * orig_shape_crop[0] / 96) + x)
    sg_l_y = int(((landmarks[19] * 48 + 48) * orig_shape_crop[1] / 96) + y)
    sg_r_x = int(((landmarks[14] * 48 + 48) * orig_shape_crop[0] / 96) + x)
    sg_r_y = int(((landmarks[15] * 48 + 48) * orig_shape_crop[1] / 96) + y)
    size_x = sg_r_x - sg_l_x
    ratio = size_x / sunglasses.shape[1]
    size_y = int(sunglasses.shape[0] * ratio)
   
    resized_sunglasses = cv2.resize(sunglasses, (size_x, size_y))
    
    x1 = sg_l_x
    x2 = sg_r_x
    y1 = sg_l_y
    y2 = sg_l_y + resized_sunglasses.shape[0]
    
    alpha_s = resized_sunglasses[:, :, 3] / 255
    alpha_l = 1.0 - alpha_s
    for c in range(0, 3):
        rgb_img[y1:y2, x1:x2, c] = (alpha_s * resized_sunglasses[:, :, c] +
                                     alpha_l * rgb_img[y1:y2, x1:x2, c])    

ax.imshow(rgb_img)
plt.show()

(Optional) Further Directions - add a filter using facial keypoints to your laptop camera

Now you can add the sunglasses filter to your laptop camera - as illustrated in the gif below.

The next Python cell contains the basic laptop video camera function used in the previous optional video exercises. Combine it with the functionality you developed for adding sunglasses to someone's face in the previous optional exercise and you should be good to go!

In [8]:
import cv2
import time 
from keras.models import load_model
import numpy as np

model_path = 'my_model_{}.h5'.format(best_optimizer_id)

face_cascade = cv2.CascadeClassifier('detector_architectures/haarcascade_frontalface_default.xml')
sunglasses = cv2.imread("images/sunglasses_4.png", cv2.IMREAD_UNCHANGED)
model = load_model(model_path)

def laptop_camera_go():
    # Create instance of video capturer
    cv2.namedWindow("face detection activated")
    vc = cv2.VideoCapture(0)

    # try to get the first frame
    if vc.isOpened(): 
        rval, frame = vc.read()
    else:
        rval = False
    
    # Keep video stream open
    while rval:
        # Plot image from camera with detections marked
        gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.25, 6)
        for (x, y, w, h) in faces:
            gray_crop = gray[y:y+h, x:x+w] 
            orig_shape_crop = gray_crop.shape
            resize_gray_crop = cv2.resize(gray_crop, (96, 96)) / 255.
            landmarks = np.squeeze(model.predict(np.expand_dims(np.expand_dims(resize_gray_crop, axis=-1), axis=0)))

            sg_l_x = int(((landmarks[18] * 48 + 48) * orig_shape_crop[0] / 96) + x)
            sg_l_y = int(((landmarks[19] * 48 + 48) * orig_shape_crop[1] / 96) + y)
            sg_r_x = int(((landmarks[14] * 48 + 48) * orig_shape_crop[0] / 96) + x)
            sg_r_y = int(((landmarks[15] * 48 + 48) * orig_shape_crop[1] / 96) + y)
            size_x = sg_r_x - sg_l_x
            ratio = size_x / sunglasses.shape[1]
            size_y = int(sunglasses.shape[0] * ratio)

            resized_sunglasses = cv2.resize(sunglasses, (size_x, size_y))

            x1 = sg_l_x
            x2 = sg_r_x
            y1 = sg_l_y
            y2 = sg_l_y + resized_sunglasses.shape[0]

            alpha_s = resized_sunglasses[:, :, 3] / 255
            alpha_l = 1.0 - alpha_s
            for c in range(0, 3):
                frame[y1:y2, x1:x2, c] = (alpha_s * resized_sunglasses[:, :, c] +
                                             alpha_l * frame[y1:y2, x1:x2, c])
            
        cv2.imshow("face detection activated", frame)
        
        # Exit functionality - press any key to exit laptop video
        key = cv2.waitKey(20)
        if key > 0: # exit by pressing any key
            # Destroy windows 
            cv2.destroyAllWindows()
            
            for i in range (1,5):
                cv2.waitKey(1)
            return
        
        # Read next frame
        time.sleep(0.05)             # control framerate for computation - default 20 frames per sec
        rval, frame = vc.read()    
        
In [ ]:
# Run sunglasses painter
laptop_camera_go()